输入:
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]]
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…
如何用'-'解析字符串到节点js本地脚本? - python我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…