如何在 Python 中仅显示列表中的重复值 [duplicate]

How to show only the Duplicate values from a List in Python [duplicate]

提问人:CatdoesPython 提问时间:9/23/2023 更新时间:9/23/2023 访问量:52

问:

我是 Python 的初学者。让我在下面向你展示我的代码,我将描述我的问题。

    random_list=['a','b','c','b','d','m','n','n']
    duplicates=[] 
    for value in random_list:
      if random_list.count(value) > 1:
        if value is not duplicates:
         duplicates. Append(value)
    

打印(重复)

以下是我运行代码时发生的情况。

    []
    ['b']
    ['b']
    ['b', 'b']
    ['b', 'b']
    ['b', 'b']
    ['b', 'b', 'n']
    ['b', 'b', 'n', 'n'

问题是它向我展示了重复项,但是,它显示的次数太多了。如何告诉 Python 我只想显示一次重复项?示例:['b','n']。请注意,我不是要消除列表中的重复项,而是要显示它们。

我已经在我的循环中尝试了不同的控件,但它们失败了。他们只显示了一个副本。

Python 数组 列出 if-statement 重复项

评论

0赞 Barmar 9/23/2023
您如何获得多个输出? 不在循环中。print(duplicates)

答:

0赞 Diego Borba 9/23/2023 #1

您可以通过检查项目在原始列表中出现的次数来创建列表:duplicates

法典
random_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates_list = list({item for item in random_list if random_list.count(item) > 1})
print(duplicates_list)
输出
['n', 'b']
3赞 Andrej Kesely 9/23/2023 #2

用于计算值和列表推导以获取重复项:collections.Counter

from collections import Counter

random_list = ["a", "b", "c", "b", "d", "m", "n", "n"]

duplicates = [c for c, v in Counter(random_list).items() if v > 1]
print(duplicates)

指纹:

['b', 'n']

评论

2赞 Blckknght 9/23/2023
使用 a 是一个非常好的主意,它会制作代码而不是(因为每次都需要扫描整个列表)。collections.CounterO(n)O(n**2)list.count
1赞 Kelly Bundy 9/23/2023
@Blckknght是的,这是顶级的。
1赞 Blckknght 9/23/2023 #3

你所拥有的内在语句已经接近于做你想做的事,但你选择了错误的比较运算符。而不是 ,你想要 .您还可以将这两个 s 组合成一个语句,其中包含:ifis notnot inifand

random_list=['a','b','c','b','d','m','n','n']
duplicates=[] 
for value in random_list:
  if random_list.count(value) > 1 and value not in duplicates:
     duplicates.append(value)
print(duplicates)