2016-02-25 45 views
0

這是最初的代碼:迭代,產生獨特的列表

word_list = ['cat','dog','rabbit'] 
letter_list = [ ] 
for a_word in word_list: 
    for a_letter in a_word: 
     letter_list.append(a_letter) 
print(letter_list) 

我需要對其進行修改以產生不同的字母的列表。

可能有人請告知如何做到這一點無需使用set()

結果應該是這樣的

> ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i'] 
+2

set有什麼問題?有任何限制嗎?你可以使用[numpy unique](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unique.html) – qmaruf

+0

如果沒有一套或其他東西靠近,你會感到複雜的O(n^2)而不是O(n),這更糟糕。 –

回答

2

,我可以看到唯一的問題是,你有沒有,如果檢查信件已經存在或不在列表中。試試這個:

>>> word_list= ['cat', 'dog', 'rabbit'] 
>>> letter_list= [] 
>>> for a_word in word_list: 
    for a_letter in a_word: 
     if a_letter not in letter_list: 
      letter_list.append(a_letter) 


>>> print letter_list 
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i'] 
+0

我如何在不使用函數的情況下執行此操作? – user1014691

+0

編輯我的答案。請檢查。 :) – Himanshu

0

使用字典,它針對基於密鑰的隨機查找進行了優化。如果遇到密鑰,請將值保留爲1。最後,在結尾處提取所有密鑰。

unique_chars = {} 
word_list = ['cat','dog','rabbit'] 
for word in word_list: 
    for alph in word: 
     unique_chars[alph] = 1 #or any other value 
letter_list = unique_chars.keys() 
1

你可以這樣做:

>>> word_list = ['cat', 'dog', 'rabbit'] 
>>> chars = [char for word in word_list for char in list(word)] # combine all chars 
>>> letter_list = [ii for n, ii in enumerate(chars) if ii not in chars[:n]] # remove duplicated chars 
>>> 
>>> print letter_list 
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i'] 

希望它能幫助。

0

所有你需要做的就是添加一個條件:

if a_letter not in letter_list 

並添加a_letter不在letter_list

的代碼如下:

word_list = ['cat','dog','rabbit'] 
letter_list = [] 

for a_word in word_list: 
    for a_letter in a_word: 
     if a_letter not in letter_list 
     letter_list.append(a_letter) 

print(letter_list) 

的輸出這將是:

['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i'] 
1

只需在第二個循環之後放置此條件:if a_letter not in letter_list