本节将学习以下内容
# 例1
gufen = []
gufen
[]
# 例2
gufen = [1, 2, "gufen"]
gufen
[1, 2, 'gufen']
即给list()函数中传入一个[]
# 例2
gufen = list()
type(gufen)
list
gufen = list([1, 2, 3, 4])
type(gufen)
list
gufen
[1, 2, 3, 4]
gufen[3:100]
[4]
gufen = list([1, 2, 3, 4])
len(gufen)
4
a = [123, 456]
b = ["gufeng", "de", "world"]
c = a + b
c
[123, 456, 'gufeng', 'de', 'world']
type(c)
list
a * 3
[123, 456, 123, 456, 123, 456]
python的索引切分,a[m:n]列举出来的是从a[m]到a[n-1]的数
a = [1, 2, 3, 4, 5, 6, 7, 8]
a[1]
2
a[-1] # -1表示倒数第一个
8
a[-2]
7
a[1:3] # 表示a[1],a[2]
[2, 3]
a[0:] # 后面的全部元素
[1, 2, 3, 4, 5, 6, 7, 8]
a[0:1]
[1]
a[:-1]
[1, 2, 3, 4, 5, 6, 7]
a = [1, 2, 3, 4, 5, 6, 7, 8]
a[0] = 789
a
[789, 2, 3, 4, 5, 6, 7, 8]
a[:] = ["gufen", "world"]
a
['gufen', 'world']
a = [1, 2, 3, 4, 5, 6, 7, 8]
del a[0] # 定点删除
a
[2, 3, 4, 5, 6, 7, 8]
del a[3:] # 范围性删除,3及后面的全部
a
[2, 3, 4]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
8 in a
True
8 not in a
False
gufen = "gufen de world"
"gufen" in gufen
True
type = [30001, 30002, 30003]
for item in type:
type = str(item)
if type not in ["30001", "30002"]:
type = "other"
print(type)
30001
30002
other
x = 1
y = 3
z = 4
z1 = [x, y, z]
sum(z1)
8
\begin{matrix} a & b & c & d & e\ f & g & h & i & j \ k & l & m & n & o \ p & q & r & s & t \end{matrix}
a = [1, 2, [3, 4]]
a
[1, 2, [3, 4]]
a[2]
[3, 4]
a[2][0]
3
a[2][1]
4
tang = ["apple", "banana", "apple", "apple", "banana"]
tang.count("banana")
2
tang = ["apple", "1", "2", "3", "4", "5"]
tang.index("apple")
0
# 没有的元素找不到
tang.index("banana")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[39], line 2
1 # 没有的元素找不到
----> 2 tang.index("banana")
ValueError: 'banana' is not in list
添加函数 append() 不限制添加元素的树结构
指定位置插入元素 insert(n,list) ,
删除指定元素remove(list)
弹出指定元素pop()
list排序sort()
反转reverse()
添加一个普通元素
gufen = []
gufen.append("gufen")
gufen
['gufen']
gufen.append(["gufen", "world"])
gufen
['gufen', ['gufen', 'world'], ['gufen', 'world']]
gufen.insert(2, "gufen") # 指定位置插入
gufen
['gufen', ['gufen', 'world'], 'gufen', ['gufen', 'world']]
gufen.insert(0, "43434")
gufen
['43434', 'gufen', ['gufen', 'world'], 'gufen', ['gufen', 'world']]
# 默认去掉这个元素的第一个
gufen.remove(['gufen', 'world'])
gufen
['43434', 'gufen', 'gufen', ['gufen', 'world']]
gufen.pop() # 默认弹出的是list的最后一个
['gufen', 'world']
# 弹出后会改变原来的list。
gufen.pop(1)
'gufen'
gufen
['43434', 'gufen']
gufen = [1, 3, 5, 6, 2, 57, 32]
gufen.sort()
gufen
[1, 2, 3, 5, 6, 32, 57]
gufen = [1, 3, 5, 6, 2, 57, 32]
gufen2 = sorted(gufen)
gufen2
[1, 2, 3, 5, 6, 32, 57]
gufen2.reverse()
gufen2
[57, 32, 6, 5, 3, 2, 1]
python专栏地址
上一篇:python-基础(3)-字符串操作
下一篇:python-基础(5)-字典操作
点个关注呗 🤪😝