List操作

2017-12-22  本文已影响24人  e85a0a8a9ba4

1.创建List

>>> list2 = [1,2,3,4]
>>> list2
[1, 2, 3, 4]

2.Append:末尾添加元素

>>> list1
[1, 2, 3, 4, 5]
>>> list1.append(6)
>>> list1
[1, 2, 3, 4, 5, 6] 
>>> list1
[1, 2, 3, 4, 5, 6]
>>> list2 = [7,8,9]
>>> list1.append(list2)
>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9]]

3.Extend:将List元素分别添加至List

>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9]]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9], 7, 8, 9]

4.Count:查询List内某个元素的个数

>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9], 7, 8, 9]
>>> list1.count(3)
1
>>> list1.append(3)
>>> list1.count(3)
2
>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9], 7, 8, 9, 3]

5.Insert:将某个元素插到List的某个位置

>>> list1.insert(0,0)
>>> list1
[0, 1, 2, 3, 4, 5, 6, [7, 8, 9], 7, 8, 9, 3]

6.Pop:删除元素

>>> list1
[0, 1, 2, 3, 4, 5, 6]
>>> list1.pop()
6
>>> list1.pop()
5
>>> list1.pop()
4
>>> list1
[0, 1, 2, 3]
>>> list1
[0, 1, 2, 3]
>>> list1.pop(2)
2
>>> list1
[0, 1, 3]

7.Remove:传递待删除元素,如果有多个元素,默认删除第一个

>>> list1
[1, 2, 3, 4, 5, 6, 3, 3, 3, 3]
>>> list1.remove(3)
>>> list1
[1, 2, 4, 5, 6, 3, 3, 3, 3]

8.Index:获取列表中某个元素的索引值

>>> list1
[1, 2, 4, 5, 6, 3, 3, 3, 3]
>>> list1.index(4)
2
>>> list1[2]
4

9.Reverse:将List元素顺序颠倒(不进行排序)

>>> list2
[2, 8, 4, 9, 0, 3, 1]
>>> list2.reverse()
>>> list2
[1, 3, 0, 9, 4, 8, 2]

10.Sort:对List元素进行排序

>>> list2
[1, 3, 0, 9, 4, 8, 2]
>>> list2.sort()
>>> list2
[0, 1, 2, 3, 4, 8, 9]

Sorted:不对原List进行排序,生成一个新的List

>>> a = [2,6,8,1,3,0,7,5,4]
>>> a
[2, 6, 8, 1, 3, 0, 7, 5, 4]
>>> b = sorted(a)
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a
[2, 6, 8, 1, 3, 0, 7, 5, 4]
上一篇 下一篇

猜你喜欢

热点阅读