python - 在给定列表中创建重复元素的新列表

标签 python python-3.x

我希望我的程序获取一个已经创建的列表,遍历它并检查是否有任何重复的元素。然后创建一个仅包含重复元素的新列表。

def repeated_elements(data):
    repeats = []
    for element in data:
        result = data.count(element)
        if result > 1:
            repeats.append(element)
       return data
print (repeated_elements([1, 2, 3, 1, 3]))#should print out [1, 3, 1, 3]
print (repeated_elements([1, 2, 3, 4, 5]))# should print out []
print (repeated_elements([5, 5, 5, 5, 5]))# should print out [5, 5, 5, 5, 5]
print (repeated_elements([10, 9, 10, 10, 9, 8]))# should print out [10, 9, 10, 10, 9]

程序最终打印出起始集

最佳答案

通过使用 collections.Counter 实现此目的的更好方法列表理解表达式为:

>>> from collections import Counter
>>> my_list = [1, 2, 3, 1, 3]

>>> my_counter = Counter(my_list)
>>> [i for i in my_list if my_counter[i]>1]
[1, 3, 1, 3]

关于python - 在给定列表中创建重复元素的新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41727941/

相关文章:

python-3.x - plotly:分组条形图中的降序

python - 你能优化这段代码吗? ( Django , python )

python - Tensorflow 2.0 : How to change the output signature while using tf. 保存模型

python - 为什么我不能将关键字参数传递给 list.index() 方法?

python - 像素点变换的性能

python - 如何从不能继承 QObject 的类发出信号?

python-3.x - Windows 10 中的 Dlib ImportError on line _dlib_pybind11 import *, DLL Load Failed

python - 替换python中二维列表中的项目

python - web2py 将值从表单发送到另一个 Controller

python - 根据列表中列的值过滤 Pandas 数据框列