在Python中获取唯一单词的列表(即,不是重复的)

2024-06-30 14:59:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含几个单词的列表,我想打印列表中唯一的单词。我说的“独特”是指在我的原始列表中只出现一次的单词。也就是说,如果一个单词出现两次(或超过两次),那么就不应该打印出来。你知道吗

以下是我的词表:

my_list = ["door", "table", "door", "chair", "couch", "door", "table", "closet"]

以下是我迄今为止尝试过的代码:

print(set(my_list))

但是,set打印一个包含所有单词的列表,尽管没有重复的单词。即:door, table, chair, couch, closet。但是,我想要的是一个类似chair, couch, closet的列表(因为它们在列表中只出现一次)。你知道吗


Tags: 代码列表mytable单词listprintset
3条回答

您可以使用Counter来实现这一点,它将创建一个字典,其中每个唯一的单词作为键,相应的出现计数作为对应的值。然后遍历字典以找到值为1的键。示例代码如下:

from collections import Counter

my_list = ["door", "table", "door", "chair", "couch", "door", "table", "closet"]

count_all = Counter(my_list)
for key, value in count_all.items():
    if 1 == value:
        print key

使用Counter虽然不是一种简单的方法,但仍然是一种很好的解决方法。计数器将计算每个项目在列表中出现的次数。你知道吗

from collections import Counter
my_list = ["door", "table", "door", "chair", "couch", "door", "table", "closet"]
my_list_count = Counter(my_list) # Counter({'door': 3, 'table': 2, 'chair': 1, 'closet': 1, 'couch': 1})

# Unique item have count = 1
print([xx for xx in my_list_count if my_list_count[xx] == 1])
# Results: ['chair', 'closet', 'couch']

你可以用-

res = [x for x in my_list if my_list.count(x) == 1]

它将返回一次出现的元素列表。你知道吗

相关问题 更多 >