输入将是:
A=['5', '5', '262.1', 0, 0.0, ['5', '5', '262.1', 0, 0.0], ['5', '5', '262.1', 0, 0.0]]
结果将是:
B=['15','15','786.3','0','0.0']
目标是[x1...xN, [y1...yN], [z1...zN]]
返回值为[x1 + y1 + z1, ..., xN + yN + zN]
答案 0 :(得分:1)
您可以按元素类型对数据进行分组:
import itertools
A=['5', '5', '262.1', 0, 0.0, ['5', '5', '262.1', 0, 0.0], ['5', '5', '262.1', 0, 0.0]]
new_a = itertools.chain.from_iterable([[list(b)] if not a else list(b) for a, b in itertools.groupby(A, key=lambda x:isinstance(x, list))])
final_result = [str(round(sum(i), 1)) for i in zip(*[map(float, i) for i in new_a])]
输出:
['15.0', '15.0', '786.3', '0.0', '0.0']
答案 1 :(得分:1)
每位用户评论:
# original input
A = ['5', '5', '262.1', 0, 0.0, ['5', '5', '262.1', 0, 0.0], ['5', '5', '262.1', 0, 0.0]]
# build a list of lists containing the non-list elements from 'A'
# i.e. it gets '5', '5', '262.1', 0, 0.0
N = [[float(item) for item in A if not isinstance(item, list)]]
# build a list of lists containing the list elements from 'A'
# i.e. it gets both ['5', '5', '262.1', 0, 0.0]
L = [list(map(float, item)) for item in A if isinstance(item, list)]
# at this point...
# N = [['5', '5', '262.1', 0, 0.0]]
# L = [['5', '5', '262.1', 0, 0.0], ['5', '5', '262.1', 0, 0.0]]
# N + L = [['5', '5', '262.1', 0, 0.0], ['5', '5', '262.1', 0, 0.0], ['5', '5', '262.1', 0, 0.0]]
# zip() iterates over each internal iterable simulatenously preforming 'sum()'
F = [sum(item) for item in zip(*(N + L))]
因此内联评论可能会有所帮助,但快速细分和链接可能对您有所帮助:
A
中的元素是否为list
对象(因为列表中有列表)float
)“映射”到A
map()
转换为list
[ ]
对象
sum()
list
的快捷方式;这是[i for i in x]
语法