Reputation: 157
I have a list with duplicate strings:
lst = ["abc", "abc", "omg", "what", "abc", "omg"]
and I would like to produce:
lst = ["3 abc", "2 omg", "what"]
so basically count duplicates, remove duplicates and add the sum to the beginning of the string.
This is how I do it right now:
from collections import Counter
list2=[]
for i in lst:
y = dict(Counter(i))
have = list(accumulate(y.items())) # creating [("omg", 3), ...]
for tpl in have: #
join_list = []
if tpl[1] > 1:
join_list.append(str(tpl[1])+" "+tpl[0])
else:
join_list.append(tpl[0])
list2.append(', '.join(join_list))
Is there a easier way to obtain the desired result in python?
Upvotes: 4
Views: 642
Reputation: 977
This is the only Pythonic way of doing it, and it is also fast.
import collections
lst = ["abc", "abc", "omg", "what", "abc", "omg"]
duplicates = collections.Counter(lst)
lst = [f"{value} {key}"
if value > 1 else key
for (key, value) in duplicates.items()]
Note: this code only works with Python 3.6+ because of the f-string syntax in the list comprehension.
Upvotes: 0
Reputation: 3258
Another possible solution with comments to help...
import operator
#list
lst = ["abc", "abc", "omg", "what", "abc", "omg"]
#dictionary
countDic = {}
#iterate lst to populate dictionary: {'what': 1, 'abc': 3, 'omg': 2}
for i in lst:
if i in countDic:
countDic[i] += 1
else:
countDic[i] = 1
#clean list
lst = []
#convert dictionary to an inverse list sorted by value: [('abc', 3), ('omg', 2), ('what', 1)]
sortedLst = sorted(countDic.items(), key=operator.itemgetter(0))
#iterate sorted list to populate list
for k in sortedLst:
if k[1] != 1:
lst.append(str(k[1]) + " " + k[0])
else:
lst.append(k[0])
#result
print lst
Output:
['3 abc', '2 omg', 'what']
Upvotes: 1
Reputation: 1308
Try this:
lst = ["abc", "abc", "omg", "what", "abc", "omg"]
l = [lst.count(i) for i in lst] # Count number of duplicates
d = dict(zip(lst, l)) # Convert to dictionary
lst = [str(d[i])+' '+i if d[i]>1 else i for i in d] # Convert to list of strings
Upvotes: 1
Reputation: 77837
You've properly used the Counter type to accumulate the needed values. Now, it's just a matter of a more Pythonic way to generate the results. Most of all, pull the initialization out of the loop, or you'll lose all but the last entry.
list2 = []
for tpl in have:
count = "" if tpl[1] == 0 else str(tpl[1])+" "
list2.append(count + tpl[0])
Now, to throw all of that into a list comprehension:
list2 = [ ("" if tpl[1] == 0 else str(tpl[1])+" ") + tpl[0] \
for tpl in have]
Upvotes: 1
Reputation: 95948
It seems you are needlessly complicating things. Here is a very Pythonic approach:
>>> import collections
>>> class OrderedCounter(collections.Counter, collections.OrderedDict):
... pass
...
>>> lst = ["abc", "abc", "omg", "what", "abc", "omg"]
>>> counts = OrderedCounter(lst)
>>> counts
OrderedCounter({'abc': 3, 'omg': 2, 'what': 1})
>>> ["{} {}".format(v,k) if v > 1 else k for k,v in counts.items()]
['3 abc', '2 omg', 'what']
>>>
Upvotes: 7