Python:容器之列表(list)

创建列表:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值