簡體   English   中英

從for循環輸出創建列表[Python]

[英]create a list from a for loop output [Python]

我有以下代碼:

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保留在文件中而保留的\\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())

如果您可以編輯上面提供的代碼,則只需添加一個列表

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

以下方法應有所幫助:

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

嘗試創建一個數組,然后將所需的值附加到該數組:

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)
with open("text2.txt", 'r') as file:
    blue_cats = [cats.strip() for cats in file if "blue" in cats.lower()]

從技術上講,到目前為止,所有答案均未達到要求的輸出。

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現在包含請求的輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM