Python 检查列表中哪些单词可以由一串字母组成

Python 检查列表中哪些单词可以由一串字母组成,python,string,list,Python,String,List,系统:Mac Python 2.7 嗨, 因此,我有一个列表,其中包含我在网上找到的英语词典中的单词。接下来,我有一个由小写字母组成的字符串。我想做的是找到列表(英语词典)中由字符串中的字母组成的所有单词,并将它们保存到单独的列表中。此外,我不希望能够重复使用字母(胶水->欢乐),但给出的字母可以重新排列。示例字符串可以是“hideg”,结果应生成一个包含以下内容的列表: ['hide','hid','hie','dig','eh','he','hi','die','ed','id','i']

系统:Mac Python 2.7

嗨, 因此,我有一个列表,其中包含我在网上找到的英语词典中的单词。接下来,我有一个由小写字母组成的字符串。我想做的是找到列表(英语词典)中由字符串中的字母组成的所有单词,并将它们保存到单独的列表中。此外,我不希望能够重复使用字母(胶水->欢乐),但给出的字母可以重新排列。示例字符串可以是“hideg”,结果应生成一个包含以下内容的列表:

['hide','hid','hie','dig','eh','he','hi','die','ed','id','i']
以下是我到目前为止得到的(注意:myWord是列表(英语词典),myLetters是字符串):


代码中的问题是,您正在比较精确匹配,在大多数情况下,这些字母没有被完全使用,即隐藏!=希德,但它当然可以构成这个词

一种简单的方法(尽管未优化)是利用,如下所示:

In [32]: from collections import Counter

In [33]: words = ['hide','hid','hie','dig','eh','he','hi','die','ed','id','i']

In [34]: letters = 'hide'

In [35]: def valid_word(words, letters):
   ....:     results = []
             # looping through words list and do a comparison
   ....:     for word in words:
                 # build a letter counter for letters
   ....:         letter_counter = Counter(letters)
                 # subtract their letter count, -ve means cannot form the word
   ....:         letter_counter.subtract(Counter(word))
   ....:         if any(c < 0 for c in letter_counter.values()):
   ....:             continue
                 # only append the result if >=0 letters left in counter
   ....:         results.append(word)
   ....:     return results
   ....: 

.subtract()做什么?还有,Counter()构成字符串的数据类型是什么?@SirPanda您可以阅读我用计数器发布的链接。它基本上是一个统计所有字母计数的工具,
subtract
将用word的字母计数器减去字母计数器,因此如果有-ve计数(这意味着没有足够的字母组成单词)应该被排除在外。
In [32]: from collections import Counter

In [33]: words = ['hide','hid','hie','dig','eh','he','hi','die','ed','id','i']

In [34]: letters = 'hide'

In [35]: def valid_word(words, letters):
   ....:     results = []
             # looping through words list and do a comparison
   ....:     for word in words:
                 # build a letter counter for letters
   ....:         letter_counter = Counter(letters)
                 # subtract their letter count, -ve means cannot form the word
   ....:         letter_counter.subtract(Counter(word))
   ....:         if any(c < 0 for c in letter_counter.values()):
   ....:             continue
                 # only append the result if >=0 letters left in counter
   ....:         results.append(word)
   ....:     return results
   ....: 
In [36]: valid_word(words, letters)
Out[36]: ['hide', 'hid', 'hie', 'eh', 'he', 'hi', 'die', 'ed', 'id', 'i']

In [37]: valid_word(words, 'hideg')
Out[37]: ['hide', 'hid', 'hie', 'dig', 'eh', 'he', 'hi', 'die', 'ed', 'id', 'i']