Python列表——去重和添加子列表元素

标签 python python-3.x nested-lists

输入:

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/

相关文章:

python - 转换字典中的嵌套列表(列表中的每个元素必须是字典中的键)

python - 解决折叠纸挑战

python - 如何在 Selenium Python 中获取标签名称?

python - 全局更改记录器模块中的日志文件名

mysql - 使用 PyMySQL 时语法无效

python - 尝试使用 urllib.retrieve : 'module' object has no attribute 'retrieve' 通过 URL 下载文件

php - 在无序列表中显示类别

python - 用科学坐标轴作图,改变有效数字的个数

python - 打印/输出时如何从列表中删除方括号

python - 用引号加入 python