我构建了一个程序,可以随机生成8个单独的字母,并将它们分配到一个名为ranlet
(随机字母的缩写)的列表中。然后,它将.txt文件导入到名为 wordslist
的列表中。随机生成字母和加载文件都可以正常工作,因为我已经单独测试了这些部分,但后来我遇到了障碍。
然后,程序必须将ranlet
列表与wordslist
列表进行比较,将匹配的单词附加到名为 hits
的列表中,并在hits
列表中显示单词
我试过这个:
for each in wordslist:
if ranlet==char in wordslist:
hits.append(wordslist)
else:
print "No hits."
print hits
可悲的是,这没有奏效。我对此还有更多变化,但都无济于事。我真的很感激对此事的任何帮助。
我认为您可以从这里的set.intersection
中受益:
set_ranlet = set(ranlet)
for word in word_list:
intersection = set_ranlet.intersection(word)
if intersection:
print "word contains at least 1 character in ran_let",intersection
#The following is the same as `all( x in set_ranlet for x in word)`
#it is also the same as `len(intersection) == len(set_ranlet)` which might
# be faster, but less explicit.
if intersection == set_ranlet:
print "word contains all characters in ran_let"
如果你
是Python
的新手,这可能是一个"容易理解"的答案:
hits = []
for word in wordslist:
if word in ranlet and word not in hits:
hits.append(word)
print hits