python小技巧-列表生成式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lxfHaHaHa/article/details/86635579

python的列表生成式用简便的方法获得list,由三个部分组成

[列表里要存的值  for遍历   判断条件]    如:

list=[x for x in range(1, 6)]
==>list=[1,2,3,4,5]

list=[x*x for x in range(1, 6)]
==>list=[1,4,9,16,25]

list=[x for x in range(1, 6) if x%2==0]
==>list=[2,4]
问题1描述:我有如下文件,想用空格分隔读取里面内容存到数组里

1.txt

a b c d

或许会这样写(其实split获得的就是一个list,这里用来举个例子):

f=open('1.txt')
list=[]
for one in f.read().split():
    list.append(one)
print(list)
f.close()

用了列表生成式可以直接如下:

f=open('1.txt')
list=[one for one in f.read().split()]
print(list)
f.close()

在这里插入图片描述

问题2描述:我有如下文件,读取不以‘#’开头的那一行内容

1.txt

#Day One
hhhhhhhhh,happy birthday
#Day Two
sad,do homework

这里的列表生成式就可以加个判断:

f=open('1.txt')
list=[one for one in f if not one.startswith('#')]
print(list)
f.close()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lxfHaHaHa/article/details/86635579
今日推荐