list列表包含以下方法:
序号 | 方法 | 作用 |
---|---|---|
1 | list.append(obj) | 在列表末尾添加新的对象 |
2 | list.count(obj) | 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) | 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) | 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) | 将对象插入列表 |
6 | list.pop([index=-1]) | 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) | 移除列表中某个值的第一个匹配项 |
8 | list.reverse() | 反向列表中元素 |
9 | list.sort(cmp=None, key=None, reverse=False) | 对原列表进行排序 |
list列表练习题:点击跳转
list切片和拼接的案例:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [3, 4, 5]
list3 += list1 + list2
print(list3)
print(list3 > list1)
print(list3[4])
print(list3[-1])
list4 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(list4[3:-6])
print(list4[3:8:2])
print(list4[3:-6:2])
print(list4[1:-6:6])
print(list4[1:8:6])
print(list4[:3] + list4[-3:])
print(list4[:-4:-1] + list4[:3])
print(list4[2:-5:3])
list5 = list((1, 2, 3, 4, 5))
print(list5)
list6 = [1, [2, 3], (1, 2)]
print(list6[2][1])
print(list6)
结果输出:
[3, 4, 5, 1, 2, 3, 1, 2, 3]
True
2
3
[4, 5, 6, 7, 8]
[4, 6, 8]
[4, 6, 8]
[2, 8]
[2, 8]
[1, 2, 3, 12, 13, 14]
[14, 13, 12, 1, 2, 3]
[3, 6, 9]
[1, 2, 3, 4, 5]
2
[1, [2, 3], (1, 2)]
list中方法的运用案例:
import copy
list1 = [1, 2, 3]
list1.append(4)
list1.append('hello')
list1.insert(4, 5)
list1 += [6]
list1.extend((7, 8))
print(list1)
list1[0] = 0
print(list1)
del list1[8]
print(list1)
list1.remove(0) # 指定数据的删除,且只删除一个
print(list1)
list1.pop() # 根据下标删除
print(list1)
list1.pop(-1)
print(list1)
print(list1.count(5))
list2 = [1, 8, 3, 4, 4, 7, 5, 2, 46, 89, 4, 6]
list2.reverse()
print(list2)
list2.sort(reverse=True)
print(list2)
list2.sort(reverse=False)
print(list2)
print(list2.index(4)) # 查找某元素第一个的下标
print(list2.index(4, 4))
print(list2.index(4, 2, 4))
list3 = [10]
list3 = list2.copy()
print(list3)
list4 = [[1, 2, 3], [2, 4, 5]]
list3 = list4.copy()
list5 = list4
list6 = copy.deepcopy(list4)
list4[0][0] = 10
print(list3)
print(list5)
print(list6)
list1.clear()
print(list1)
运行结果:
[1, 2, 3, 4, 5, ‘hello’, 6, 7, 8]
[0, 2, 3, 4, 5, ‘hello’, 6, 7, 8]
[0, 2, 3, 4, 5, ‘hello’, 6, 7]
[2, 3, 4, 5, ‘hello’, 6, 7]
[2, 3, 4, 5, ‘hello’, 6]
[2, 3, 4, 5, ‘hello’]
1
[6, 4, 89, 46, 2, 5, 7, 4, 4, 3, 8, 1]
[89, 46, 8, 7, 6, 5, 4, 4, 4, 3, 2, 1]
[1, 2, 3, 4, 4, 4, 5, 6, 7, 8, 46, 89]
3
4
3
[1, 2, 3, 4, 4, 4, 5, 6, 7, 8, 46, 89]
[[10, 2, 3], [2, 4, 5]]
[[10, 2, 3], [2, 4, 5]]
[[1, 2, 3], [2, 4, 5]]
[]
list推导式:
x = ['赵', '钱', '孙', '李']
m = ['1', '2', '3', '4']
name = [i+j for i in x for j in m]
print(name)
运行结果:
[‘赵1’, ‘赵2’, ‘赵3’, ‘赵4’, ‘钱1’, ‘钱2’, ‘钱3’, ‘钱4’, ‘孙1’, ‘孙2’, ‘孙3’, ‘孙4’, ‘李1’, ‘李2’, ‘李3’, ‘李4’]
list的遍历方法:
# 遍历列表 100 97 94 91 88 85
list1 = [i for i in range(100, 84, -3)]
print(list1)
for i in range(0, len(list1)):
print(list1[i])
for i in range(-len(list1), 0):
print(list1[i])
for i in list1:
print(i)