创建列表:
money = [] # 空列表
age = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 整型(int)
fruit = ["apple", "banana", "orange"] # 字符串(string)
列表长度:
age = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
len(age) # 列表长度:10
遍历列表:
disease = ['HBP', 'T2DM', 'HUA']
"""方法1"""
for item in disease:
print(item)
"""方法2"""
for index, item in enumerate(disease):
print(index, item)
提取元素:
age = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
age[0] # 提取首个元素:1
age[-1] # 提取末位元素:10
age[1:5] # 提取第2至第5个元素:[2, 3, 4, 5]
# 访问<5的元素
# 方法1
result = [item for item in age if item < 5]
print(result) # 输出:[1, 2, 3, 4]
# 方法2
result = []
for item in age:
if item < 5:
result.append(item)
print(result) # 输出:[1, 2, 3, 4]
添加元素:
age = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
age.append(11) # 在列表末尾添加一个新元素11
print(age) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
列表解包:
age = [1, 2, 3]
a, b, c = age
print(a) # 输出:1
print(b) # 输出:2
print(c) # 输出:3
money = [1, [2, 3], 4]
x, y, z = money
print(x) # 输出:1
print(y) # 输出:[2, 3]
print(z) # 输出:4
money = [1, [2, 3], 4]
a, (b, c), d = money
print(a) # 输出:1
print(b) # 输出:2
print(c) # 输出:3
print(d) # 输出:4