- 创建列表
- 列表操作
- 列表的索引
- 列表排序
- 列表删除
- 列表的迭代与搜索
- 列表的推导式
names = [ 'Elwood', 'Jake', 'Curtis' ] nums = [ 39, 38, 42, 65, 111]列表操作
names.append('Murphy') # Adds at end
names.insert(2, 'Aretha') # Inserts in middle
‘ + ’ 连接列表
s = [1, 2, 3] t = ['a', 'b'] s + t # [1, 2, 3, 'a', 'b']列表的索引
names = [ 'Elwood', 'Jake', 'Curtis' ] names[0] # 'Elwood' names[1] # 'Jake' names[2] # 'Curtis'列表排序
s = [10, 1, 7, 3] s.sort() # [1, 3, 7, 10] # Reverse order s = [10, 1, 7, 3] s.sort(reverse=True) # [10, 7, 3, 1] s = ['foo', 'bar', 'spam'] s.sort() # ['bar', 'foo', 'spam']列表删除
names.remove('Curtis')
#或
del names[1]
列表的迭代与搜索
for name in names:
# e.g. print(name)
...
列表的搜索
names = ['Elwood','Jake','Curtis']
names.index('Curtis') # 2
列表的推导式
一般语法。
[for in if ]
列表推导来自数学(集合构建符号)。
a = [ x * x for x in s if x > 0 ] # Python
a = { x^2 | x ∈ s, x > 0 } # Math



