# Python列表操作

1，列表的基本操作
1.2修改列表，给元素赋值

x= [1,1,1]
x[1] = 2
x
[1, 2, 1]
1.3删除元素

names = [‘Alice’, ‘Beth’, ‘Cecil’, ‘Dee-Dee’, ‘Earl’]
del name
del names[2]
names
[‘Alice’, ‘Beth’, ‘Dee-Dee’, ‘Earl’]
1.4给切片赋值

names = [‘Alice’, ‘Beth’, ‘Cecil’, ‘Dee-Dee’, ‘Earl’]
del name
name names

del names[2]
names
[‘Alice’, ‘Beth’, ‘Dee-Dee’, ‘Earl’]

number = [1,5]
number[1:1] = [2,3,4]
number
[1, 2, 3, 4, 5]

1.5函数list

list(‘Hello’)
[‘H’, ‘e’, ‘l’, ‘l’, ‘o’]

2，列表方法

2.1 append

lst = [1, 2, 3]
lst.append(4)
lst
[1, 2, 3, 4]

2.2 clear

lst = [1,2,3]
ls
lst
lst.clear()
lst
[]

2.3 copy

a = [1,2,3]
b = a
b[1] = 4
a
[1, 4, 3]

a = [1,2,3]
b = a.copy()
b[1] = 4
a
[1, 2, 3]

b
[1, 4, 3]

2.4 count

[‘to’, ‘be’, ‘or’, ‘not’, ‘to’, ‘be’].count(‘to’)
2

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

x.count([1, 2])
1

x[3].count([1, 2]) 统计x类表中第4个元素出现列表[1, 2]的次数
1

2.5 extend

a = [1,2,3]
b = [4,5,6]
a.extend(b) 将列表b作为参数提供给extend方法。
a
[1, 2, 3, 4, 5, 6] 这里a的值已经改变。

a = [1,2,3]
b
[4, 5, 6]
a + b
[1, 2, 3, 4, 5, 6]
a
[1, 2, 3] 这里并没有改变列表a的值

2.6 index

knights = [‘we’, ‘are’, ‘the’, ‘knigts’, ‘who’, ‘say’, ‘ni’]
knights.index(‘who’)
4

knights.index(‘xr’)
Traceback (most recent call last):
File “”, line 1, in
ValueError: ‘xr’ is not in list

2.7 insert

numbers = [1,2,3,5,6,7]
numbers.insert(3, ‘four’) 注意这里必须是两个参数，第一个是插入的位置，第二个 是值
numbers
[1, 2, 3, ‘four’, 5, 6, 7]

2.8 pop

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

x
[1, 2]

x.pop(0)
1

x
[2]

Push和pop是两种栈操作。Python没有提供push，可使用append来替代。方法pop和append的效果相反。

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

x.append(x.pop(1)) # pop取出第2个元素2后，被append加到列表后面了。
x
[1, 3, 2]

2.9 remove

x = [‘to’, ‘be’, ‘or’, ‘not’, ‘to’, ‘be’]
x.remove(‘be’)
x
[‘to’, ‘or’, ‘not’, ‘to’, ‘be’] #只删除第一个匹配到的值。

2.10 reverse

x = [1,2,3]
x.reverse()
x
[3, 2, 1]

x
[1, 2, 3]

list(reversed(x))
[3, 2, 1]

2.11 sort

x = [4,7,2,5,8,1,3]
x.sort()
x
[1, 2, 3, 4, 5, 7, 8]

x = [4,7,2,5,8,1,3]
y = x.sort() #x.sort()不返回任何值，所以y是空的。
y
None

x = [4,7,2,5,8,1,3]
y = x.copy()
y.sort()
x
[4, 7, 2, 5, 8, 1, 3]

y
[1, 2, 3, 4, 5, 7, 8]

x = [4,7,2,5,8,1,3]
y = sorted(x) 该函数会返回一个列表，可以赋值给y
x
[4, 7, 2, 5, 8, 1, 3]

y
[1, 2, 3, 4, 5, 7, 8]

2.12 高级排序

x = [‘aardsfgew’, ‘abcdefg’, ‘iopl’, ‘yut’, ‘create’]
x.sort(key=len)
x
[‘yut’, ‘iopl’, ‘create’, ‘abcdefg’, ‘aardsfgew’]

x = [4,7,2,5,8,1,3]
x.sort(reverse = True) sort是从小到大进行排序，reverse将结果翻转过来。
x
[8, 7, 5, 4, 3, 2, 1]
Reverse = False是什么结果？结果就是从小到大进行排序。而不是不排序。

x = [4,7,2,5,8,1,3]
x.sort(reverse = False) # reverse = False意思是不翻转。
x
[1, 2, 3, 4, 5, 7, 8]

05-18 2万+

10-18 805
10-27 2219
12-12 3743
09-09 6849
02-22 506
06-13 8724
03-15 134
06-03 1240
11-02 34万+
10-16 3934
07-31 1万+
09-29 3万+
02-05 1万+
04-12 1721
08-14 23万+
09-29