[英]How to create a list out of this for-loop 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()
我想知道如何將這個循環的結果保存在列表中。 謝謝!
.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()
您可以閱讀所有行,然后使用簡單的列表理解。
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.