【问题标题】:create a list from a for loop output [Python]从 for 循环输出创建列表 [Python]
【发布时间】:2016-03-09 13:17:08
【问题描述】:

我有这个代码:

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 cats
  • 是的,我只想要blue cats
  • 在遍历行时不能追加到列表吗?
  • 如果在其余的下面还有另一个blue cats 怎么办。您是要包含 all blue cats 行,还是仅包含彼此重叠的行。
  • 我完全不知道 append 是如何工作的,我是新手。

标签: python list python-3.x for-loop


【解决方案1】:

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

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,因为它位于文件中,您可能不想要它。最后,为了确保您始终找到“蓝色”,您希望通过在要搜索的字符串上使用 lower() 来强制小写:

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

【讨论】:

  • 列表理解比追加更快。如果您想以两者中最有效的方式进行操作,请使用答案的顶部。
  • @JohnSmith 没错。答案的第二部分是让 OP 更深入地了解正在发生的事情以及他们需要对代码进行哪些更改才能使其正常工作。
【解决方案2】:

如果您可以编辑上面提供的代码,您可以简单地添加一个列表

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

【讨论】:

    【解决方案3】:

    以下方法应该会有所帮助:

    with open("text2.txt", 'r') as f_input:
        output = [row.strip() for row in f_input if row.startswith("blue cat")]
    
    print(', '.join(output))
    

    这将打印:

    blue cat 2, blue cat 5, blue cat 3
    

    【讨论】:

      【解决方案4】:

      尝试创建一个数组,然后将所需的值附加到该数组:

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

      【讨论】:

        【解决方案5】:
        with open("text2.txt", 'r') as file:
            blue_cats = [cats.strip() for cats in file if "blue" in cats.lower()]
        

        【讨论】:

          【解决方案6】:

          从技术上讲,到目前为止,没有一个答案会产生所请求的输出。

          OP 要求输出如下:

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

          这是一个单元素列表,包含一个“逗号和空格”分隔的字符串,仅包含输入文件中的“蓝猫”

          怀疑这是一个错字,但也许不是。

          所以要正确回答问题,这里有一些代码:

          with open("text2.txt", 'r', encoding='utf_8') as openfile:
              cats = [line.strip() for line in openfile if 'blue' in line.lower()]
          mystring = ""
          for cat in cats:
              mystring += ', ' + cat
          mylist = []
          mylist.append (mystring[2:])
          

          mylist 现在包含请求的输出

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2023-04-01
            • 2021-02-08
            • 1970-01-01
            • 1970-01-01
            • 2013-05-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多