[英]How to create a list out of this for-loop code?
This should not be too hard, I just really cannot figure it out.这不应该太难,我真的想不通。 I have this set of code:
我有这组代码:
file_open=open('mbox-short.txt','r')
counter=0
for line in file_open:
if line.startswith('From:') and line.find('localhost')==-1:
counter+=1
line.strip()[6:]
file_open.close()
I am wondering how I can save the results of this loop in a list.我想知道如何将这个循环的结果保存在列表中。 Thank you!
谢谢!
.append() to append eleman to list .append() 到 append eleman 到列表
file_open=open('mbox-short.txt','r')
list = []
counter=0
for line in file_open:
if line.startswith('From:') and line.find('localhost')==-1:
counter+=1
list.append(line.strip()[6:])
file_open.close()
https://docs.python.org/3/c-api/list.html https://docs.python.org/3/c-api/list.html
You could read all the lines in and then use a simple list comprehension.您可以阅读所有行,然后使用简单的列表理解。
with open('mbox-short.txt','r') as file_open:
lines = file_open.readlines()
lst = [line.strip()[6:] for line in lines if line.startswith('From:') and line.find('localhost')==-1]
print(lst)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.