我想验证数据并使用两个列表执行一些数学运算。首先,我想确保每个列表的第一个元素匹配,然后我想通过第一个列表的第二个项目多次第二个列表的第二个,第三个和第四个项目。我想创建一个新列表,然后对该列表的元素求和。
列表看起来像这样:
lista = [(1, 500), (2, 600), (3, 333)]
listb = [(1, 10, 11, 10.5), (2, 99, 100, 100), (3, 50, 51, 50)]
在创建listc之前,我想确保每个子列表的第一个元素在列表之间匹配。然后我想得到一个列表,它将看起来像的元素倍增:
listc = [(1, 5000, 5500, 5250), (2, 59400, 60000, 60000), (3, 16650, 16983, 16650)]
然后我想创建一个第四个列表,其中元素相加,如下:
listd = [(6 (doesn't necessarily have to sum this element), 81050, 81650, 81900)]
我一直在研究" zip"功能。我知道该函数可以进行乘法运算,但它如何进行验证呢?
答案 0 :(得分:-1)
你可以在Python3中试试这个:
from functools import reduce
lista = [(1, 500), (2, 600), (3, 333)]
listb = [(1, 10, 11, 10.5), (2, 99, 100, 100), (3, 50, 51, 50)]
if not all(c == d for (c, e), (d, *h) in zip(lista, listb)) or len(lista) != len(listb) or any(any(b is None for b in i) for i in lista) or any(any(b is None for b in i) for i in listb):
raise ValueError("lists not validated")
new_listing = [(c, *[d*i for i in e]) for (c, d), (h, *e) in zip(lista, listb) if c == h]
final_listing = [reduce(lambda x, y:(x[0]+y[0], *[a+b for a, b in zip(x[1:], y[1:])]), new_listing)]
print(new_listing)
print(final_listing)
输出:
[(1, 5000, 5500, 5250.0), (2, 59400, 60000, 60000), (3, 16650, 16983, 16650)]
[(6, 81050, 82483, 81900.0)]
修改强>
对初始输入进行排序的解决方案:
from functools import reduce
lista = [(1, 500), (2, 600), (3, 333)]
listb = [(1, 10, 11, 10.5), (2, 99, 100, 100), (3, 50, 51, 50)]
lista = sorted(lista, key=lambda x:x[0])
listb = sorted(listb, key=lambda x:x[0])
new_listing = [(c, *[d*i for i in e]) for (c, d), (h, *e) in zip(lista, listb) if c == h]
final_listing = [reduce(lambda x, y:(x[0]+y[0], *[a+b for a, b in zip(x[1:], y[1:])]), new_listing)]
编辑2:
Python 2.7解决方案:
lista = [(1, 500), (2, 600), (3, 333)]
listb = [(1, 10, 11, 10.5), (2, 99, 100, 100), (3, 50, 51, 50)]
if not all(c == d[0] for (c, e), d in zip(lista, listb)) or len(lista) != len(listb) or any(any(b is None for b in i) for i in lista) or any(any(b is None for b in i) for i in listb):
raise ValueError("lists not validated")
new_listing = [tuple([c]+[d*i for i in h[1:]]) for (c, d), h in zip(lista, listb) if c == h[0]]
final_listing = [reduce(lambda x, y:tuple([x[0]+y[0]]+[a+b for a, b in zip(x[1:], y[1:])]), new_listing)]