lst = [['category1', 12], ['category2', 78], ['category3', 8], ['category2', 53], ['category4', 894]]
tmp = []
for item in lst:
if item[0] in [i[0] for i in tmp]: # to check if ithis category is already present in the new list
for itm in tmp: # if yes, locate it and add the integer value
if itm[0] == item[0]:
itm[1] += item[1]
else: # if not, simply append that item to new list
tmp.append(item)
print(tmp)
你可以用熊猫图书馆来整理清单
使用这种技术是很有帮助的,因为aggfunc对于其他应用程序来说更棒!:D个
O/p公司
如果你想用列表和迭代来完成,你可以从
输出:
但我必须说,
dict
技术更直观,在较长列表中的性能更好。你知道吗您可以创建一个
defaultdict
并使用列表中的值更新字典,如下所示:如果你想让它回到
list
:相关问题 更多 >
编程相关推荐