如何根据python中的每个位置添加嵌套列表元素

时间:2018-04-11 20:28:55

标签: python

输入将是:

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]

的列表

2 个答案:

答案 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))]

因此内联评论可能会有所帮助,但快速细分和链接可能对您有所帮助:

  • isinstance检查A中的元素是否为list对象(因为列表中有列表)
  • map执行其名称所暗示的内容,它将函数(float)“映射”到A
  • 中的每个列表元素
  • list用于将结果从map()转换为list
  • 显示的[ ]对象
  • zip同时迭代多个iterables,以便我们可以在迭代器上调用sum()
  • list comprehension是制作list的快捷方式;这是[i for i in x]语法