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

标签 python

我有一个包含几个单词的列表,我想打印该列表中的唯一单词。我所说的“独特”单词是指在我的原始列表中只出现一次的单词。也就是说,如果一个单词出现两次(或两次以上),则不应打印它。

这是我的单词列表:

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

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

print(set(my_list))

但是,set 会打印包含所有单词的列表,但没有重复项。即:门、 table 、椅子、沙发、壁橱。然而,我想要的是一个像椅子、沙发、壁橱这样的列表(因为它们在列表中只出现一次)。

最佳答案

通过使用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']

关于python - 在 Python 中获取唯一单词(即不重复)的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53075856/

相关文章:

python - Return-if-value 习语(条件返回)

python - DOCTEST==argv[0] 作为约定?

python - 在 Facebook API 上获取用户访问 token

python - Flask-sqlalchemy group_by 具有最大 id

python - 在 Pandas 数据帧 .loc 中使用 Python 的 `in` 运算符

c# - 如何将 Python 脚本嵌入到 C# 程序中?

python - 如何在python中找到大于均值的列表的最长连续子序列

python - 使用 Python 检查未读的 Gmail 邮件数

python - 使用多个列表作为函数的输入参数 (Python)

python - 将 Python 应用程序作为 debian 包分发,但作为服务分发