列表操作
list函数:
[python] view plaincopy
- >>> list(‘hello‘)
- [‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘]
改变列表:
[python] view plaincopy
- >>> x=[1,1,1]
- >>> x[1]=2
- >>> x
- [1, 2, 1]
删除元素:
[python] view plaincopy
- >>> names = [‘wu‘,‘li‘,‘zhao‘,‘qian‘]
- >>> del names[1]
- >>> names
- [‘wu‘, ‘zhao‘, ‘qian‘]
分片赋值:
[python] view plaincopy
- >>> name = list(‘perl‘)
- >>> name
- [‘p‘, ‘e‘, ‘r‘, ‘l‘]
- >>> name[2:] = list(‘ar‘)
- >>> name
- [‘p‘, ‘e‘, ‘a‘, ‘r‘]
[python] view plaincopy
- >>> num = [1,2,3,4,5]
- >>> num[1:4]=[] #从1位开始但不包括4位
- >>> num
- [1, 5]
append 列表末尾添加新元素:
[python] view plaincopy
- >>> lst = [1,2,3]
- >>> lst.append(4)
- >>> lst
- [1, 2, 3, 4]
count 统计元素的个数:
[python] view plaincopy
- >>> [‘we‘,‘have‘,‘we‘,‘a‘,‘dog‘].count(‘we‘)
- 2
extend 扩展列表:
[python] view plaincopy
- >>> a = [1,2,3]
- >>> b = [4,5,6]
- >>> a.extend(b)
- >>> a
- [1, 2, 3, 4, 5, 6]
index 找出第一个匹配项的位置:
[python] view plaincopy
- >>> sentence = [‘I‘,‘have‘,‘a‘,‘little‘,‘dog‘]
- >>> sentence.index(‘little‘)
- 3
insert 将对象插入列表:
[python] view plaincopy
- >>> num = [1,2,3,5,6,7]
- >>> num.insert(3,‘four‘)
- >>> num
- [1, 2, 3, ‘four‘, 5, 6, 7]
pop 移除列表元素,默认最后一个:
[python] view plaincopy
- >>> x = [1,2,3]
- >>> x.pop()
- 3
- >>> x
- [1, 2]
- >>> x.pop(0)
- 1
- >>> x
- [2]
结合append:
[python] view plaincopy
- >>> x = [1,2,3]
- >>> x.append(x.pop())
- >>> x
- [1, 2, 3]
remove 移除列表中的第一个匹配项:
[python] view plaincopy
- >>> x = [‘to‘,‘be‘,‘or‘,‘not‘,‘to‘,‘be‘]
- >>> x.remove(‘be‘)
- >>> x
- [‘to‘, ‘or‘, ‘not‘, ‘to‘, ‘be‘]
reverse 反向存放元素:
[python] view plaincopy
- >>> x = [1,2,3]
- >>> x.reverse()
- >>> x
- [3, 2, 1]
sort 排序:
[python] view plaincopy
- >>> x = [4,6,2,1,7,9]
- >>> x.sort()
- >>> x
- [1, 2, 4, 6, 7, 9]
[python] view plaincopy
- >>> x.sort(reverse=True)
- >>> x
- [9, 7, 6, 4, 2, 1]
- >>> x.sort(reverse=False)
- >>> x
- [1, 2, 4, 6, 7, 9]
时间: 2024-12-10 03:15:41