简体   繁体   中英

Python - Comparing a list of characters to a list of words?

I have built a program that randomly generates 8 separate letters and assigns them into a list called ranlet (short for random letters). It then imports a .txt file into a list called wordslist . Both the random generation of letters and loading the file works fine, as I have tested these parts individually, but then I hit a snag.

The program then must compare the ranlet list to the wordslist list, append the matching words to a list called hits and display the words in the hits list

I tried this:

for each in wordslist:
    if ranlet==char in wordslist:
        hits.append(wordslist)
    else:
        print "No hits."

print hits

Sadly, this didn't work. I have many more variations on this, but all to no avail. I would really appreciate any help on the matter.

I think you could benefit from set.intersection here:

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"

If you are new at Python , this may be an 'easy to understand' answer:

hits = []
for word in wordslist:
    if word in ranlet and word not in hits:
        hits.append(word)
print hits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM