如何从列表中提取所有重复值?

时间:2019-06-03 09:18:34

标签: python

我有以下列表:friends = ["Brian","John","Brian", "Alena", "Brian"]。如果我使用duplicated(),我只会得到 Brian 一次,但结果应该是Brian, Brian, Brian(因为该列表包含该名称的次数是3次)。

2 个答案:

答案 0 :(得分:1)

尝试一下:

dups = [f for f in friends if friends.count(f) > 1]

答案 1 :(得分:0)

 # you can try this     
  from collections import Counter
  count =  [count for item, count in Counter(friends).items() if count > 1] # this will 
   give you the count of the duplicated item
  item   =  [item for item, count in Counter(friends).items() if count > 1] # this will 
  return the item itself