PK Stroh :
Input:
a = [[['a','b'],3],[['b','a'],9],[['b','z'],4]]
Desired Output (dedupe regardless of order and add integers)
[[['a','b'],12],[['b','z'],4]]
This does not work of course:
a2 = [sorted(list) for list in [i[0] for i in a]]
print(a2)
[['a', 'b'], ['a', 'b'], ['b', 'z']]
which can be deduped of course:
a3= []
for i in a2:
if i not in a3:
a3.append(i)
print(a3)
[['a', 'b'], ['b', 'z']]
But of course I am losing the counts for the sub-list being deduped.
Any advice?
Thanks.
Eric Frigade :
I guess this is what you want:
a = [[['a','b'],3],[['b','a'],9],[['b','z'],4]]
# we use a dict to do the job.
# we sort the list of char and change to tuple. So i can be use as key.
dct = {}
for i in a:
srt = tuple(sorted(i[0]))
if srt in dct:
# the tuple of char is already existing as key, just sum int.
dct[srt]+= i[1]
else:
# if not we had a new key
dct[srt] = i[1]
# Convert the dict to list of list
new_list = [[list(k),v] for k,v in dct.items()]
print(new_list) # [[['a', 'b'], 12], [['b', 'z'], 4]]
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=379376&siteId=1