Python 1.2 Python内置数据结构-列表、字典和集合

一. List创建、索引、遍历和内置增删函数

  1.列表是Python的内置可变对象,由Array实现,支持任意类型的添加、组合和嵌套。

L = [] # L = list()
L = [1, 1.024, 'dsp']
# List对象的引用的修改会造成原List的改变,需要copy()或者创建一个新的list对象(L[:]) title
= L.copy() # shollow copy title = M[:] #索引 FROM 0 to len(L)-1,类似C语言数组。并支持反向索引 ->L[:-1] L[i:j]

print(L[::-1])
print( len(L), L[0:1], L[0:-1], L[0:] )

   2. 列表的插入增添元素操作: append()  insert() 数组移动导致开销过大,O(n)复杂度) extend(), 原地修改,不返回值

# Add element: 1.append 2.insert 3.extend 
L.append('AI') # append object to end 
L.append('CS')

ex = ['python','C++','html']
L.extend(ex)   # extend iterable object, L.extend("1")
L += ['php', 'go', 'java', 'javascript'] # 被解释器优化为extend()操作
L.insert(-1,'ML') # L.insert(index, object) -- insert object before index L.insert(0,"football") L.insert(len(l)-1,'real')

  3. 查找和删除操作: L.index()  L.count()  pop(index) remove() 

# search and find pos
L.index('python')  # return first index of value
L.count('python')  # return number of occurrences of value计数

# Delete elemnt: 1.pop 2.remove 3.del 4.clear

# L.pop([index]) -> item: remove and return item at index (default last)
L.pop() 
print(L.pop(0))

L_new = L.remove('dsp') # remove first occurrence of value移除第一个
print(L_new)

del L[0:2]
L_new.clear() # L.clear() -> None -- remove all items 
L print(L_new)

  4.排序: 列表解析和 sort、reverse 方法

L = [x for x in ('a', 'b', 'c', 'd', 'e')] 
alpha = list( map(ord , L) )
for i, a in zip(L, alpha):
  print( i, "ord", a)


# 原处修改 L.sort() L.reverse()--> no return
#
L.sort(key=None, reverse=False) -> None -- stable sort IN PLACE
L_new.sort() print("sort in palce", L_new)
L_new.sort(reverse
=True)
print("reverse sort in place", L_new) print( sorted(L_new) )


# 返回一个新的对象
L_new.reverse()

# L.reverse() -- reverse *IN PLACE*

print(L_new) M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# get column 2

col2 = [row[1] for row in M] title = L

二 . Dict创建、修改和内置增删函数

  1.字典类型由哈希表实现,具有快速查找的特点。

       字典的key值必须是不可变元素如字符、数字和元组对象,Python中可动态的增加字典元素。

  字典创建的几种方法:

#[1] 声明创建 dict
D0 = {"id":1, 'info': {'name':'David', 'age':20, 'sex':'M'}}

#[2] 空字典不断添加键值
D1 = {}
D1['id'] = 2  # 通过键获取value
D1['info'] = {'name':'Mick', 'age':17, 'sex':'F'}

D1['id'] = 5 # 复制修改value
print( D0.get("id", 0) ) # D.get(key, defautl)方式取值,避免无键异常
if 'info' in D3:
    print('exist ', D3['info'])

#[3] 元组键值对赋值创建
D2 = dict( [('id', 3), ('info', {'name':'Lucy', 'age':16, 'sex':'F'}) ])

#[4] 键必须是string, 形如 key=value pairs的参数
D3 = dict( age = 4, text = {'name':'David', 'socre':666 } )

#[5] values equal
D4 = dict.fromkeys(['a', 'b'], 0) # 创建字典:键不同,值相同

#[6] 字典生成式
alpha = { chr( i+ord('a') ):i+ord('a') for i in range(26) }

   或者通过两个Values和Keys列表输入内置zip函数,得到形如(key,value)的zip对象。

keys = [ 'a', 'b', 'c' ]
values = [ 5, 6, 7 ]
D = {}
for key, value in zip( keys, values):
    D[key] = value
# 直接通过zip键值对赋值 D = dict( zip( keys, values) )

  2.  其他增删函数 update()  |  pop(key)

#  内置方法获取键keys()、值values()
print( list( D0.keys() ) )
print( list( D0.values() ))
print( list( D0.items() ))

D1.update(D0)
print( D2.pop('info') )

  3. 字典解析、遍历 

D = dict( k:0 for k in ['a', 'b'] ) 

# zip-->together keys and values, it returns a key-vlaue pairs
print( zip( ['a', 'b', 'c'], [1, 2, 3] ) ) 
D = dict( zip(['a', 'b', 'c'], [1, 2, 3]) )
D = { k:v for k, v in zip(['a', 'b', 'c'], [1, 2, 3]) }
alpha = { i: chr( ord('a')+i-1 ) for i in range(1,27) }
# 迭代
ks = D.keys() # 为可迭代对象Iterable
ks.sort()
for k in ks:
    print(k, '->', D[k])
for k in sorted( D.keys() ):
    print(k, D[k])

# dictionary key exchange with value
def changedict(dic):  
    mydict = {}  
    for key in dic:  
        mydict.update({}.fromkeys(dic[key],key))  
    return mydict
# 键值交换
def revert_dict( d ):
   new_dict = { }
    for key in d.keys():
      new_dict[ d[key] ] = key
     return new_dict
print( revert_dict(alpha) )

3. Python的Set

    Python集合也是基于hash实现的,set中的元素必须是不可变对象(hashable)。

    set支持集合操作(求交集i、并集、差集,判断是子集、超集)

    添加元素 add、update 删除元素pop、remove、clear

a = set()
a.add(1)   
a.add('a')
a.update(list(range(8, 15)))
# {1, 8, 9, 10, 11, 12, 13, 14, 'a'}
print(len(a), a.__sizeof__())     # 9

# 当集合不为空,移除第一个元素(实际有序)
a.pop()
if a.__contains__(10):
    a.remove(10)      # 移除集合中的指定元素

c = a.copy()          # 得到a的拷贝
a.clear()
b = set(list(range(10)))
a.__contains__(1)     # 检查集合是否包含对应元素

print(a.intersection(b))
print(a.union(b))
print(a.difference(b))

# 参考《python 学习手册》

# 转载请注明来源:  https://www.cnblogs.com/justLittleStar/p/10417760.html

原文地址:https://www.cnblogs.com/justLittleStar/p/10417760.html