简体   繁体   English

迭代以生成唯一列表

[英]Iterating to produce a unique list

This is the initial code:这是初始代码:

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)

I need to modify it to produce a list of unique letters.我需要修改它以生成一个唯一字母列表。

Could somebody please advise how to do this without using set()有人可以建议如何在不使用 set() 的情况下做到这一点

The result should be like this结果应该是这样的

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

Only problem that I can see is that you have not checked if the letter is already present in list or not.我能看到的唯一问题是你没有检查这封信是否已经出现在列表中。 Try this:尝试这个:

>>> 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']

You can do like this:你可以这样做:

>>> 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']

Hope it helps.希望能帮助到你。

只需放置此条件: if a_letter not in letter_list在第二个 for 循环之后if a_letter not in letter_list

Use a dictionary, it is optimized for key based random look-ups.使用字典,它针对基于键的随机查找进行了优化。 Keep the value as 1 if the key is encountered.如果遇到键,则将该值保留为 1。 Finally, extract all the keys at the end.最后,提取最后的所有密钥。

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()

All you have to do is add a condition :您所要做的就是添加一个条件:

if a_letter not in letter_list

And add the a_letter is not in the letter_list并添加a_letter不在letter_list

The code is as follows :代码如下:

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)

The output for this would be :输出将是:

['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
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)


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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