names = ['Michael', 'Bob', 'Tracy'] nums = [1, 2, 3]
也可以使用其他方法split()创建
split()
line = 'Hello World!' row = line.split(' ') row # ['Hello', 'World!']
names.append('Adam') # 在末尾添加元素 names.insert(1, 'Jack') # 在指定位置添加元素
使用+连接两个列表
+
s=[1,2,3] t=[4,5,6] s+t # [1,2,3,4,5,6]
列表索引从 0 开始
names = ['Michael', 'Bob', 'Tracy'] names[0] # Michael names[1] # Bob names[-1] # Tracy
使用索引覆盖元素
names[0] = 'Adam' # 修改第一个元素 names # ['Adam', 'Bob', 'Tracy']
使用len获取列表长度
len
len(names) # 3
使用in判断元素是否在列表中
in
'Adam' in names # True 'manon' in names # False
使用for循环遍历列表
for
for name in names: print(name)
查找索引值
names.index('Bob') # 1
使用del或remove删除元素
del
remove
names.remove('Bob') # 删除第一个 Bob del names[0] # 删除第一个元素
使用sort对列表进行排序
sort
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] # It works with any ordered data s = ['foo', 'bar', 'spam'] s.sort() # ['bar', 'foo', 'spam']
使用sorted创建新的列表,不会修改原列表
sorted
t = sorted(s)