簡體   English   中英

如何使用Python在給定的字母列表中搜索單詞列表

[英]How to search list of words for a given list of letters using Python

我有以下信件清單:

letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']

以及以下單詞列表:

words = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']

如果字母列表中存在任何單詞組合,如何使用Python搜索? 就像只看它一樣,我們可以觀察到兩個單詞“ yutz”和“ tux”是唯一可以用於我們擁有的字母列表的單詞。

我是Python的新手,我嘗試過使用不同的for循環,但無法到達任何地方。

for word in words:
    for i in letters:
        if i in word:
            print(word)
        else:
            print('not in word')

你們可以理解,結果就是災難。

您需要從集合的角度看問題。 words列表中屬於字母集的子集的任何單詞都可以由這些字母組成。 換句話說, letters必須是單詞的超集:

letters = {'t', 'u', 'v', 'w', 'x', 'y', 'z'}  # a set, not a list
for word in words:
    if letters.issuperset(word):
        print(word)

如果可迭代參數的所有元素都在集合中,則set.issuperset()方法將返回true。

如果您想要一個列表,只需使用列表理解:

[word for word in words if letters.issuperset(word)]

演示:

>>> words = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']
>>> letters = {'t', 'u', 'v', 'w', 'x', 'y', 'z'}  # a set, not a list
>>> [word for word in words if letters.issuperset(word)]
['yutz', 'tux']

請注意,這只看唯一的字母 appleletters集合{'a', 'p', 'l', 'e'} 如果您也需要處理字母計數 ,則需要使用多集 Python有一個稱為collections.Counter()的實現。 這樣不僅可以跟蹤字母,還可以跟蹤它們的數量。

Counter類型不支持對子集或超集的測試,因此您必須使用減法。 如果產生一個空的Counter() ,則整個單詞可以由字母計數組成:

letters = Counter(['a', 'p', 'l', 'e', 'p', 'i'])
words = ['apple', 'applepie']
for word in words:
    if not Counter(word) - letters:
        print(word)

或作為列表理解:

[word for word in words if not Counter(word) - letters]

產生['apple'] ,因為輸入字母多集中只有一個'e' ,只有2個'p' ,而不是3個。

您可以在此處使用set.difference

r = [w for w in words if not set(w).difference(letters)]

r
['yutz', 'tux']

如果結果為空集,則意味着w每個字符都屬於letters 在這種情況下, set.difference返回一個空的set ,它是False -y,所以not ....結果為True並打印單詞。 這等效於:

for w in words:
    if not set(w).difference(letters):
        print(w)

yutz
tux

這類似於使用set.issuperset進行測試,但是從另一個角度解決了該問題。

您可以將all函數與生成器一起使用,以確定屬於words的單詞中的所有字符是否都存在於letters

letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']
words = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']
final_words = [i for i in words if all(c in letters for c in i)]

輸出:

['yutz', 'tux']

您可以使用itertool的排列方法:

一行:

print(set(["".join(permutation) for item in words for permutation in itertools.permutations(letters,len(item)) if "".join(permutation) in words ]))

詳細解決方案:

上面的列表理解與:

words = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']

letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']
import itertools

final=[]
for i in words:
    for k in itertools.permutations(letters,len(i)):
        if "".join(k) in words and "".join(k) not in final:
            final.append("".join(k))

print(final)

輸出:

['yutz', 'tux']

暫無
暫無

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

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