列表
列表是Python中最具灵活性的有序集合对象类型。
# 列表迭代和解析
>>> res = [c*4 for c in 'Spam']
>>> res
['SSSS', 'pppp', 'aaaa', 'mmmm'
>>> res = []
>>> for c in 'Spam':
... res.append(c*4)
...
>>> res
['SSSS', 'pppp', 'aaaa', 'mmmm']
>>> list(map(abs,[-1,-2,0,1,2]))
[1, 2, 0, 1, 2]
# 一般操作
>>> L = [5,3,6,2,8]
>>> sorted(L)
[2, 3, 5, 6, 8]
>>> L
[5, 3, 6, 2, 8]
>>> L.sort()
>>> L
[2, 3, 5, 6, 8]
>>> L.insert(0,1)
>>> L
[1, 2, 3, 5, 6, 8]
>>> L.reverse()
>>> L
[8, 6, 5, 3, 2, 1]
>>>
>>> del L[0]
>>> L
[6, 5, 3, 2, 1]
>>> L.pop()
1
>>> L
[6, 5, 3, 2]
>>> L.remove(6)
>>> L
[5, 3, 2]
'''
原处修改列表:因为Python只处理对象引用,所以需要将原处修改一个对象与生成的一个新对象区分开来。
因为在原处修改一个对象时,可能同时会影响一个以上指向它的引用。
'''
# 其他
>>> L = ['already','got','one']
>>> L
['already', 'got', 'one']
>>> L[1:]=[]
>>> L
['already']
>>> L[0]=[]
>>> L
[[]]
字典
如果把列表看成是有序的对象集合,字典可以当成是无序的集合。主要区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
>>> D = {'food':{'ham':1,'egg':2}}
>>> D.get('food')
{'ham': 1, 'egg': 2}
>>> D2 = {'a':1,'b':2}
>>> D.update(D2)
>>> D
{'food': {'ham': 1, 'egg': 2}, 'a': 1, 'b': 2}
>>> D.pop('b')
2
>>> len(D)
2
>>> D
{'food': {'ham': 1, 'egg': 2}, 'a': 1}
>>> del D['a']
>>> D
{'food': {'ham': 1, 'egg': 2}}
>>> D = {x:x*2 for x in range(10)}
>>> D
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
>>> D = {'spam':2,'ham':1,'eggs':3}
>>> D['spam']
2
>>> D
{'spam': 2, 'ham': 1, 'eggs': 3}
>>> len(D)
3
>>> 'ham' in D
True
>>> list(D.keys())
['spam', 'ham', 'eggs']
>>> list(D.values())
[2, 1, 3]
>>> D
{'spam': 2, 'ham': 1, 'eggs': 3}
>>> D['ham']=['grill','bake','fry']
>>> D无锡看男科医院哪家好 https://yyk.familydoctor.com.cn/20612/
{'spam': 2, 'ham': ['grill', 'bake', 'fry'], 'eggs': 3}
>>> del D['eggs']
>>> D
{'spam': 2, 'ham': ['grill', 'bake', 'fry']}
>>> D['brunch'] = 'Bacon'
>>> D
{'spam': 2, 'ham': ['grill', 'bake', 'fry'], 'brunch': 'Bacon'}
>>> list(D.items())
[('spam', 2), ('ham', ['grill', 'bake', 'fry']), ('brunch', 'Bacon')]
>>> D2 = {'toast':4,'muffin':5}
>>> D.update(D2)
>>> D
{'spam': 2, 'ham': ['grill', 'bake', 'fry'], 'brunch': 'Bacon', 'toast': 4, 'muffin': 5}
>>> table = {'Python':'Guido van Rossum',
... 'Perl':'Larry Wall',
... 'Tcl':'John Ousterhout'}
>>>
>>> language = 'Python'
>>> creator = table[language]
>>> creator
'Guido van Rossum'
>>> for lang in table:
... print(lang,' ',table[lang])
...
Python Guido van Rossum
Perl Larry Wall
Tcl John Ousterhout
# 三种方法来避免missing-key错误
... if (2,3,6) in Matrix:
... print(Matrix[(2,3,6)])
... else:
... print(0)
...
0
>>>
>>>
>>> try:
... print(Matrix[(2,3,6)])
... except KeyError:
... print(0)
...
0
>>>
>>>
>>> Matrix.get((2,3,4),0)
98
>>> Matrix.get((2,3,6),0)
0