这里我有一个元组列表,只要键为空,我想将对应值添加到其前一个元组值。
我能够以传统方式实现这一目标,但它看起来很难看, 是否有任何pythonic方法来实现相同的目标?
输入:
data= [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]
预期产出:
[13, 26, 39, 52]
我的代码:
data = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]
init = 0 ; splitdata = []
for i in data:
init = init+i[1]
if i[0] == '':
splitdata.append(init)
splitdata.append(init)
print(splitdata)
[13, 26, 39, 52]
答案 0 :(得分:1)
manage_pages
这种减少......
reduce(
lambda lst,item: (((item[0] != '') and lst) or lst[:-1]) + [lst[-1] + item[1]],
colLabelGrouped[1:],
[colLabelGrouped[0][1]] )
中第一项的值,然后是colLabelGrouped
中的剩余项目...
答案 1 :(得分:1)
这里使用accumulate函数和list-comprehensions(它可能更具可读性)的方式稍微短一点:
colLabelGrouped = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]
from itertools import accumulate
cumsum = list(accumulate([x[1] for x in colLabelGrouped]))
result = [cumsum[i] for i,x in enumerate(colLabelGrouped) if x[0] == ""]
if colLabelGrouped[-1][0] != "":
result.append(cumsum[-1])
print(result)
答案 2 :(得分:1)
使用reduce可以执行以下操作:
from functools import reduce
data = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]
splitdata = reduce(
lambda res, i: res[:-1] + [res[-1] + i[1]] * (2 if i[0] == '' else 1),
data,
[0]
)
print(splitdata)