我已经构建了一个程序,该程序随机生成8个单独的字母,并将它们分配到名为ranlet
的列表中(随机字母的缩写)。然后,它将.txt文件导入名为wordslist
的列表中。随机生成字母和加载文件都可以正常工作,因为我已经单独测试了这些部分,但后来遇到了障碍。
然后,程序必须将ranlet
列表与wordslist
列表进行比较,将匹配的单词追加到名为hits
的列表中,并在hits
列表中显示单词< / p>
我试过了:
for each in wordslist:
if ranlet==char in wordslist:
hits.append(wordslist)
else:
print "No hits."
print hits
可悲的是,这没用。我对此有很多变化,但都无济于事。我真的很感激有关此事的任何帮助。
答案 0 :(得分:3)
我认为你可以从这里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"
答案 1 :(得分:2)
如果您是Python
的新用户,这可能是一个“易于理解”的答案:
hits = []
for word in wordslist:
if word in ranlet and word not in hits:
hits.append(word)
print hits