我有一个列表列表:
ls = [['01',2,3,4], ['02',5,2,4], ['03',2,6,4], ['01',1,3,4]]
我想在该字符串之后添加该子列表的术语,并从相同的字符串开始的所有其他子列表中添加相应的术语。
所以结果应该像这样:
result = [['01',3,6,8], ['02',5,2,4], ['03',2,6,4]]
# the first and last original sublists were "combined"
我尝试了以下代码:
ls=[['01',2,3,4],['02',5,2,4],['03',2,6,4],['01',1,3,4]]
totals = {}
for key, value1,value2,value3 in ls:
totals[key] = totals.get(key, 0) + value1
totals[key] = totals.get(key, 0) + value2
totals[key] = totals.get(key, 0) + value3
print(totals)
但这不是我的目标:
{'01': 17, '02': 11, '03': 12}
答案 0 :(得分:0)
对您的代码进行少量修改,当有新的“键”时,我已经初始化了值[0, 0, 0]
。
ls = [['01', 2, 3, 4],['02', 5, 2, 4],['03', 2, 6, 4],['01', 1, 3, 4]]
totals = {}
for key, value1, value2, value3 in ls:
if key not in totals.keys():
totals[key] = [0, 0, 0]
totals[key][0] += value1
totals[key][1] += value2
totals[key][2] += value3
totals = [[k] + v for k, v in totals.items()]
print(totals)
# Output:
# [['01', 3, 6, 8], ['02', 5, 2, 4], ['03', 2, 6, 4]]
您的代码的第一个问题是,当您拥有新密钥时,totals.get(key, 0)
不会给您0
我们想要的初始值[0, 0, 0]
。
第二,您要在for循环中对列表的所有值求和,而不是逐个元素地对列表求和。因此,您得到{'01': 17, '02': 11, '03': 12}
版本2(更通用,可处理非数字)
ls = [['01', 2, 'a', 4],['02', 5, 2, 4],['03', 2, 6, 4],['01', 1, 'ad', 4]]
totals = {}
for x in ls:
if x[0] not in totals.keys():
totals[x[0]] = x[1:]
else:
for i in range(len(totals[x[0]])):
if isinstance(x[1 + i], (int, float)):
totals[x[0]][i] += x[1 + i]
totals = [[k] + v for k, v in totals.items()]
print(totals)
# Output:
# [['01', 3, 'a', 8], ['02', 5, 2, 4], ['03', 2, 6, 4]]
答案 1 :(得分:0)
您可以使用setdefault以及一些索引来获得所需的结果。
.well-known
编辑以处理出现字符而选择第一个字符的情况
ls=[['01',2,3,4],['02',5,2,4],['03',2,6,4],['01',1,3,4]]
totals = {}
for element in ls:
key ,array = element[0],element[1:]
for index in range(len(array)):
totals.setdefault(key,[0]*len(array))[index] += array[index]
result = []
for key,value in totals.items():
result.append([key] + value)
print(result)
# you can sort the result to get exactly as you wanted
# you dont need this step if the dictionary is already sorted like in python3
result.sort(key=lambda x:x[0])
print(result)
输出
在python 2中
ls=[['01',2,'a',4],['02',5,2,4],['03',2,3,4],['01',1,'asd',4]]
totals = {}
for element in ls:
key ,array = element[0],element[1:]
for index in range(len(array)):
if key not in totals:
totals.setdefault(key,array)
elif (type(totals[key][index]) == "int") and type(array[index] == "int"):
totals[key][index] += array[index]
result = []
for key,value in totals.items():
result.append([key] + value)
print(result)
# you can sort the result to get exactly as you wanted
# you dont need this step if the dictionary is already sorted like in python3
result.sort(key=lambda x:x[0])
print(result)
在python 3中
[['02', 5, 2, 4], ['03', 2, 6, 4], ['01', 3, 6, 8]]
[['01', 3, 6, 8], ['02', 5, 2, 4], ['03', 2, 6, 4]]
答案 2 :(得分:0)
如果我收到您的问题,则您实际上是在尝试按数组求和的方式进行分组。就个人而言,我会这样做:
sum_dictionary = {}
for ls in your_list:
key = ls[0]
vals = ls[1:]
if key not in sum_dictionary:
sum_dictionary[key] = [vals]
else:
sum_dictionary[key].append(vals)
for k, v in sum_dictionary.items():
sum_dictionary[k] = list(map(sum, zip(*v)))
答案 3 :(得分:0)
使用groupby
from itertools
也许更优雅一些:
steps {
sh'''
...
AA=XXX
BB=YYY
set > vars.prop
'''
script {
vars = readProperties file: 'vars.prop'
env << vars // merge vars into env
echo 'AA='+ env['AA']
}
}
请注意,上述解决方案将对原始列表from itertools import groupby
from operator import itemgetter
ls = [['01', 2, 3, 4], ['02', 5, 2, 4], ['03', 2, 6, 4], ['01', 1, 3, 4]]
res = []
for k, group in groupby(sorted(ls), itemgetter(0)):
group = [sub[1:] for sub in group]
res.append([k] + [sum(x) for x in zip(*group)])
print(res) # -> [['01', 3, 6, 8], ['02', 5, 2, 4], ['03', 2, 6, 4]]
进行排序!