Reputation: 433
I have two lists
populate_name = ['jack', 'Jill', 'Mary', 'Franco', 'jack', 'James', 'Dan', 'Mary']
populate_qty = ['2', '3', '1', '3', '4', '4', '3', '3']
I want to output the name whose cumulatively added qty
is maximum.
In this case:
jack = (2 + 4) # 6
Jill = 3
Mary = (1 + 3) # 4
Franco = 3
James = 4
Dan = 3
The winner here is jack
, so how do I print out the name, i.e jack
and its value i.e 6
.
I tried to run through the list and find the occurrences of each of the elements using populate_name.count(populate_name)
but that's just to find the occurrence. Moreover it will repeat if I run the for loop in the entire range(len(populate_name))
.
NOTE
The populate_name and populate_qty in the actual code consists of more than 1K elements.
Upvotes: 2
Views: 64
Reputation: 397
import operator
def max_populate(populate_name, populate_qty):
d = {}
for i in zip(populate_name, populate_qty):
if i in d:
d[i[0]] += i[1]
else:
d[i[0]] = i[1]
return max(d.iteritems(), key=operator.itemgetter(1))
Upvotes: 0
Reputation: 7418
You can use the Python built-in function zip
and the dict
data structure to get your result:
result = {}
for name, qty in zip(populate_name, populate_qty):
result[name] = result.get(name, 0) + int(qty)
name, qty = sorted(result.items(), key=lambda o: o[1])[-1]
So then you get your winner:
>>> print(name) # name
'jack'
>>> print(qty) # qty
6
Upvotes: 2
Reputation: 179392
Use collections.Counter
!
import collections
counter = collections.Counter()
for name, qty in zip(populate_name, populate_qty):
counter[name] += qty
print counter.most_common()[0][0]
Upvotes: 3