1、列表的增加元素的四种方法:
#append>>> list1=['a','b''c']>>> print (list1.append('d'))None
>>> (list1.append('d')) >>> print(list1) ['a', 'bc', 'd', 'd'] >>> #insert 根据索引增加元素: >>> list1=['a','c'] >>> list1.insert(1,'b') >>> list1 ['a', 'b', 'c'] #extend 用一个列表遍历添加在另外一个列表之后: >>> list1=['a','b','c'] >>> list1.extend(['d','e']) #参数是列表 >>> list1 ['a', 'b', 'c', 'd', 'e'] # ‘+’ 有返回值,上面的都没有 >>> list1=['a','b','c'] >>> list2=['d','e'] >>> print(list1+list2) ['a', 'b', 'c', 'd', 'e']
#实例:比较extend和append 的不同之处
>>> list1=['a','b','c','d']
>>> list1.append(['e','f'])
>>> print(list1)
['a', 'b', 'c', 'd', ['e', 'f']]
>>> list1=['a','b','c','d']
>>> list1.extend(['e','f'])
>>> print(list1)
['a', 'b', 'c', 'd', 'e', 'f']
2、列表的切片
格式:【start:end:step】,step:步长,end-start,步长为正时,从左向右取值。步长为负时,反向取值。包头不包尾。
>>> list1=['a','b','c','d'] >>> print(list1[1:3]) ['b', 'c'] >>> print(list1[1::2]) ['b', 'd'] >>> print(list1[::-2]) ['d', 'b']
3、列表长常用方法:
#1、清空列表: >>> list1=['a','b','c','d'] >>> list1.clear() >>> list1 [] #2、复制列表 >>> list1=['a','b','c','d'] >>> list2=list1.copy() >>> list2 ['a', 'b', 'c', 'd'] #3、计算元素出现的次数: >>> list1=['a','b','c','d','a'] >>> print(list1.count('a')) 2 #4、求已知元素的下标
>>> list1=['a','b','c','d']
>>> print(list1.index('a'))
0
#5、pop() 删除某个值(1.指定索引;2. 默认最后一个),并获取删除的值,即有返回值
>>> list1=['a','b','c','d']
>>> print(list1.index('a'))
0
>>> list1=['a','b','c','d']
>>> print(list1.pop())
d
>>> print(list1.pop(1))
b
>>> print(list1)
['a', 'c']
#6、remove方法
>>> list1=['a','b','c','d']
>>> list1.remove()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly one argument (0 given)
>>> list1.remove('a')
>>> list1
['b', 'c', 'd']
#7、列表的反转
>>> list1=['a','b','c','d']
>>> list1.reverse()
>>> list1
['d', 'c', 'b', 'a']
#8、列表的排序:
>>> list1=[2,55,6,87]
>>> list1.sort()
>>> print(list1)
[2, 6, 55, 87]
>>> list1.sort(reverse=True)
>>> list1
[87, 55, 6, 2]
#9、列表删除元素
>>> list1=[1,2,3]
>>> del(list1[1])
>>> print(list1)
[1, 3]
#10、in 方法:
>>> list1=['a','b','c']
>>> print('a' in list1)
True
#列表和字符串之间的转化:
>>> str1='abc'
>>> print(list(str1))
['a', 'b', 'c']
!!!!
>>>>>> ls=[1,2,3]
>>> print(str(ls))
[1, 2, 3]
>>> print(type(str(ls)))
<class 'str'> #即生成的是’[1, 2, 3]'
>>> list1=['a','b','c']
>>> print(''.join(list1))
abc