输入:
a = [[['a','b'],3],[['b','a'],9],[['b','z'],4] ]
期望的输出(不考虑顺序去重并添加整数)
[[['a','b'],12],[['b','z'],4]]
这当然行不通:
a2 = [sorted(list) for list in [i[0] for i in a]]
print(a2)
[['a', 'b'], ['a', 'b'], ['b', 'z']]
当然可以去重:
a3= []
for i in a2:
if i not in a3:
a3.append(i)
print(a3)
[['a', 'b'], ['b', 'z']]
当然,我正在丢失子列表的重复数据删除计数。
有什么建议吗?
谢谢。
最佳答案
我想这就是你想要的:
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]]
关于Python列表——去重和添加子列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60894538/