簡體   English   中英

Python 比較兩個列表,如果單詞匹配添加到另一個列表

[英]Python compare two lists, if words match add to another list

我試圖將“單詞”與“if_contains”進行比較,當它們匹配時,它們應該被添加到保存列表中。 預期 output - ['一','二八九']。 output 我得到 - ['one']

if_contains = ['one', 'two', 'three']
save = []
words = ['one', 'five', 'six', 'two eight nine']

for word in words:
    if word in if_contains:
        save.append(words)

print(save)

第一件事是您保存整個單詞列表而不是單個元素。 你可能想做

save.append(word)

代替

save.append(words)

其次,如果你想保存two eight nine作為匹配if_contains列表,那么不要執行if word in if_contains ,你應該詢問if_contains的任何元素是否在word中(這不是最好的選擇變量名,因為它偶爾代表幾個詞)。 最終解決方案:

if_contains = ['one', 'two', 'three']
save = []
words = ['one', 'five', 'six', 'two eight nine']

for word in words:
    for el in if_contains:
        if el in word:
            save.append(word)

print(save)

您將整個列表附加到save列表變量。 使用save.append(word)而不是save.append(words)

if_contains = ['one', 'two', 'three']
save = []
words = ['one', 'five', 'six', 'two eight nine']

for word in words:
    if word in if_contains:
        save.append(word)

print(save)

請看一下。 單詞有錯誤,您需要使用嵌套循環。

if_contains = ['one', 'two', 'three']
save = []
words = ['one', 'five', 'six', 'two eight nine']

for if_c in if_contains:
    for word in words:
        if if_c in word:
            save.append(word)

print(save)

使用list comprehension

if_contains = ['one', 'two', 'three']
save = []
words = ['one', 'five', 'six', 'two eight nine']

[word for word in words if word in if_contains]
['one']

呃,但如果我只想得到整個單詞而不是 substring?

if_contains = ['napoli', 'salvini', 'one']
save = []
words = ['napoli', 'pierosalvini', 'stellone', 'pietrone']

for word in words:
    for el in if_contains:
        if el in word:
            save.append(word)

print(save)

在這種情況下,我擁有所有帶有子字符串的單詞。 但我想要那不勒斯,因為它是 100% 匹配的。 所有字符必須相同。

謝謝

試圖解決:

p_calcio01=open('parole_calcio.txt')
p_calcio = [line.rstrip('\n') for line in p_calcio01]

for row in frame:
    for word in p_calcio:
        for word1 in frame["Cleaned Text into list"]: #words list in a dataframe
            if word1 in word:
                 frame["Cluster"] = "Calcio"
frame

parole_calcio.txt 是每行的簡單單詞列表。 Dataframe 是:在此處輸入圖像描述

frame["Cluster"]是一個新列

暫無
暫無

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

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