Skip to main content
 首页 » 编程设计

python之从 for 循环输出创建列表 [Python]

2025年05月04日18findumars

我有这个代码:

with open("text2.txt", 'r') as file:         
    for cats in file: 
        if "blue" in cats:  
            print (cats) 

text2.txt 文件如下所示:

blue cat 3  
blue cat 2  
blue cat 5  
red cat 2  
green cat 2  
blue cat 3 
yellow cat 5  

我想得到一个如下所示的列表:

["blue cat 3, blue cat 2, blue cat 5, blue cat 3"]  

“手工制作列表”对我来说不是一个选项,我正在处理一个大文件,所以这不是我的问题的解决方案:

mylist = ["blue cat 3, blue cat 2, blue cat 5, blue cat 3"] 

请您参考如下方法:

这可以很容易地通过列表理解来完成。您只是遍历文件中的每一行,只保留其中包含“blue”的行:

with open("text2.txt", 'r') as file: 
    n = [i.strip() for i in file if 'blue' in i.lower()] 
 
print(n) 

将输出:

['blue cat 3', 'blue cat 2', 'blue cat 5', 'blue cat 3'] 

要扩展以上内容的工作原理并将其与您的代码相关联:

其实你离得并不远。您在解决方案中唯一缺少的是实际创建一个列表并附加到它:

因此,创建一个空列表:

blue_cats = [] 

然后保持您的代码不变,但是更改 print (cats) 以附加到您的。请注意,我使用了 strip()。这将删除保留在字符串中的 \n,因为它在文件中,您可能不需要它。最后,作为确保始终找到“blue”的额外好处,您希望通过在要搜索的字符串上使用 lower() 强制小写:

blue_cats = [] 
with open("text2.txt", 'r') as file:         
    for cats in file: 
        if "blue" in cats.lower():  
            blue_cats.append(cats.strip())