欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python列表推导式使用

程序员文章站 2024-01-06 13:58:28
...
****#**列表推导式******
alist=[]#一般的操作方式
for x in range(30):
    alist.append(x+x)
print(alist)
alist=[x+x for x in range(30)]#使用列表推导式,形式上更加简洁
print(alist)
freshfruit=['banana','apple','oregan']
alist=[]#一般的操作方法
for x in freshfruit:
    alist.append(x.strip())
print(alist)
alist=[x.strip() for x in freshfruit]#使用列表推导式方法
print(alist)
#使用列表推导式实现嵌套列表的平铺
vec=[[1,2,3],[4,5,6],[7,8,9]]#一般的方法
result=[]
for elem in vec:#遍历列表中的子列表
    for num in elem:#遍历子列表里的元素
        result.append(num)
print(result)
vec=[[1,2,3],[4,5,6],[7,8,9]]
x=[num for elem in vec for num in elem]
print(x)

结果输出

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58]
['banana', 'apple', 'oregan']
['banana', 'apple', 'oregan']
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

上一篇:

下一篇: