这是初始代码:
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']
答案 0 :(得分: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']
答案 1 :(得分: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']
希望它有所帮助。
答案 2 :(得分:1)
只需在第二个for循环后放置此条件:if a_letter not in letter_list
。
答案 3 :(得分: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()
答案 4 :(得分: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']
答案 5 :(得分:0)
li = [char for word in word_list for char in word] # create list with individual characters
li_without_duplicates = list(dict.fromkeys(li)) #remove duplicates
print(li_without_duplicates)