I have the following list: friends = ["Brian","John","Brian", "Alena", "Brian"]
. If I use duplicated()
I only get Brian one time, but the result should be Brian, Brian, Brian
(because the list contains that name three times).
Asked
Active
Viewed 463 times
0
-
Does order matter? E.g. should `["A", "B", "A", "B", "C"]` output `["A", "B", "A", "B"]` or `["A", "A", "B", "B"]` (or something else)? – TrebledJ Jun 03 '19 at 09:37
-
The output should be ["A", "A", "B", "B"]. So, the order does matter. – bogdann Jun 03 '19 at 10:07
2 Answers
1
Try this:
dups = [f for f in friends if friends.count(f) > 1]

goodvibration
- 5,980
- 4
- 28
- 61
-
Good! If i have a column within an csv file that contains all the values from above, how can i get the same result ? data["Friends"] = [f for f in data["Friends"] if data["Friends"].count(f) > 1] # i've tried like this and it doesn't worked. – bogdann Jun 03 '19 at 09:44
-
The error is KeyError: 'Level (output omitted) must be same as name (None)' – bogdann Jun 03 '19 at 10:40
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

basilisk
- 1,156
- 1
- 14
- 34