基于 Python 中的条件对嵌套列表求和 [英] Sum nested lists based on condition in Python

查看:37
本文介绍了基于 Python 中的条件对嵌套列表求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的嵌套列表:

I have a nested list looking like this:

[['Vienna','2012', 890,503,70],['London','2014', 5400, 879,78],
 ['London','2014',4800,70,90],['Bern','2013',300,450,678], 
 ['Vienna','2013', 700,850,90], ['Bern','2013',500,700,90]]

如果城市和年份相等,我想要做的是将子列表中的每个整数值与另一个子列表相加.一开始想到了以city和year为key的字典,结果排序出现问题.

What I want to do is summing every integervalue in the sublist with another sublist if city and year are equal. I first thought of a dictionary with city and year as key, but it caused problems sorting it.

然后我有:{('Vienna','2012'):[890,503,70],('Bern','2013'):[800,1150,768],...}

我也试过这样的:

[sum(x) for x in zip(*list) if x[0] == x[0]] 但当然没有用.

我可以用嵌套列表做这样的事情,以便按城市和年份对其进行排序会更容易吗?

Can I do something like this with a nested list to so sorting it by city and year would be easier?

推荐答案

您可以构造一个结果 dict 其中键是原始列表中前两项的元组,值是 list 的数字.每次向 dict 添加值时,您都可以使用 get 返回现有元素或给定默认值,在本例中为空列表.

You could construct a result dict where key is tuple of first two items in the original lists and value is list of numbers. Every time you add value to dict you could use get to either return existing element or given default value, in this case empty list.

一旦您拥有要添加的现有列表和列表,您就可以使用 zip_longestfillvalue 从两个列表中获取要求和的数字.zip_longest 返回长度为 2 的元组,其中包含每个列表中的一个数字.如果一个列表比其他列表长,fillvalue 被用作默认值,因此这也适用于列表具有不同长度的情况.最后,列表推导式可用于对每个项目求和以获得新值:

Once you have the existing list and list to add you can use zip_longest with fillvalue to get numbers to sum from both lists. zip_longest returns tuples of length 2 containing one number from each list. In case one list is longer than other fillvalue is used as default so this will also work in case lists have different lengths. Finally list comprehension could used to sum each item for a new value:

from itertools import zip_longest

l = [
    ['Vienna','2012', 890,503,70],['London','2014', 5400, 879,78],
    ['London','2014',4800,70,90],['Bern','2013',300,450,678],
    ['Vienna','2013', 700,850,90], ['Bern','2013',500,700,90]
]

res = {}
for x in l:
    key = tuple(x[:2])
    res[key] = [i + j for i, j in zip_longest(res.get(key, []), x[2:], fillvalue=0)]

print(res)

输出:

{('Vienna', '2013'): [700, 850, 90], ('London', '2014'): [10200, 949, 168], 
 ('Vienna', '2012'): [890, 503, 70], ('Bern', '2013'): [800, 1150, 768]}  

如果您想先按字母顺序对城市进行排序,并首先对年份进行排序,您可以将自定义 key 传递给 sorted:

If you want to sort the cities alphabetically and years latest first you could pass custom key to sorted:

for item in sorted(res.items(), key=lambda x: (x[0][0], -int(x[0][1]))):
    print(item)

输出:

(('Bern', '2013'), [800, 1150, 768])
(('London', '2014'), [10200, 949, 168])
(('Vienna', '2013'), [700, 850, 90])
(('Vienna', '2012'), [890, 503, 70])

这篇关于基于 Python 中的条件对嵌套列表求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆