Python入门篇之列表和元组

2019-10-05 15:30:36丽君

2
>>> x=[[1,2],1,1,[2,1,[1,2]]]
>>> x.count(1)
2
>>> x.count([1,2])
1

3、extend

extend方法可以在列表的末尾一次性的追加另一个序列中的多个值


>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
>>> #区别连接操作
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a+b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3]

4、index

index方法用于从列表中找出某一个匹配项的索引位置:


>>> knights=['we','are','the','knigths','who','say','ni']
>>> knights.index('who')
4
>>> knights=['we','are','the','knigths','who','say','ni']
>>> knights.index('herring')

Traceback (most recent call last):
  File "<pyshell#184>", line 1, in <module>
    knights.index('herring')
ValueError: 'herring' is not in list

没有成功找到会引发异常

 5、insert

insert方法用于将对象插入到列表中:


>>> numbers=[1,2,3,5,6,7]
>>> numbers.insert(3,'four')
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]
>>> #extend方法一样,insert方法的操作也可以用分片赋值来实现
>>> numbers=[1,2,3,5,6,7]
>>> numbers[3:3]=['four']
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]

6、pop

pop方法会移除列表中的一个元素(默认是最后一个),并且返回该元素的值:


>>> x=[1,2,3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]

注意:pop方法是唯一一个既能修改列表又返回元素值(除了None)的列表方法

7、remove

remove方法用于移除列表中某个值的第一个匹配项:


>>> x=['to','be','or','not','to','be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
>>> x.remove('bee')

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    x.remove('bee')
ValueError: list.remove(x): x not in list

8、reverse

reverse方法将列表中的元素反向存放,该方法也改变了列表但不返回值


>>> x=[1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]
9、sort

sort方法用于在原位置对列表进行排序,改变原来的列表,从而让其中的元素按照一定的


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