首页 > 代码库 > Beginning Python From Novice to Professional (3) - 列表操作

Beginning Python From Novice to Professional (3) - 列表操作

列表操作

list函数:

>>> list('hello')
['h', 'e', 'l', 'l', 'o']
改变列表:

>>> x=[1,1,1]
>>> x[1]=2
>>> x
[1, 2, 1]
删除元素:

>>> names = ['wu','li','zhao','qian']
>>> del names[1]
>>> names
['wu', 'zhao', 'qian']
分片赋值:

>>> name = list('perl')
>>> name
['p', 'e', 'r', 'l']
>>> name[2:] = list('ar')
>>> name
['p', 'e', 'a', 'r']
>>> num = [1,2,3,4,5]
>>> num[1:4]=[] #从1位开始但不包括4位
>>> num
[1, 5]
append 列表末尾添加新元素:

>>> lst = [1,2,3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
count 统计元素的个数:

>>> ['we','have','we','a','dog'].count('we')
2
extend 扩展列表:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
index 找出第一个匹配项的位置:

>>> sentence = ['I','have','a','little','dog']
>>> sentence.index('little')
3
insert 将对象插入列表:

>>> num = [1,2,3,5,6,7]
>>> num.insert(3,'four')
>>> num
[1, 2, 3, 'four', 5, 6, 7]
pop 移除列表元素,默认最后一个:

>>> x = [1,2,3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]
结合append:

>>> x = [1,2,3]
>>> x.append(x.pop())
>>> x
[1, 2, 3]
remove 移除列表中的第一个匹配项:

>>> x = ['to','be','or','not','to','be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
reverse 反向存放元素:

>>> x = [1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]
sort 排序:

>>> x = [4,6,2,1,7,9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
>>> x.sort(reverse=True)
>>> x
[9, 7, 6, 4, 2, 1]
>>> x.sort(reverse=False)
>>> x
[1, 2, 4, 6, 7, 9]

Beginning Python From Novice to Professional (3) - 列表操作