2012-11-19 39 views
4

我建立了一個程序,它隨機生成8個獨立的字母,並將它們分配到一個名爲ranlet(隨機字母縮寫)的列表中。然後它將一個.txt文件導入名爲wordslist的列表。隨機生成字母和加載文件都很好,因爲我已經單獨測試了這些部分,但後來我遇到了麻煩。Python - 比較字符列表和單詞列表?

然後程序必須在ranlet列表比作wordslist列表,追加匹配的單詞一個叫hits列表和hits列表

我想這顯示的話:

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

print hits 

可悲,這不起作用。我有更多的變化,但都無濟於事。我真的很感謝在這個問題上的任何幫助。

+2

顯示示例數據,輸入輸出。 – Marcin

+0

聽起來像一個拼字遊戲,與朋友的話或類型代碼。也許你應該搜索python拼字遊戲的實現,看看那裏做了什麼。 –

回答

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" 
+0

讓我知道如何改善這一點,我很樂意更新:) – mgilson

2

如果你是新的Python,這可能是一個「很容易理解的回答:

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