Python - 将字符列表与单词列表进行比较?

时间:2012-11-19 15:27:21

标签: python string compare words letters

我已经构建了一个程序,该程序随机生成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
可悲的是,这没用。我对此有很多变化,但都无济于事。我真的很感激有关此事的任何帮助。

2 个答案:

答案 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