简体   繁体   English

在python中添加列表索引

[英]adding list indexes in python

Say I have this list: 说我有这个清单:

[['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]

And I want to add together the final element of each array (.12 and .13), how do I convert these strings to a real number, and add them together? 我想将每个数组的最后一个元素(.12和.13)加在一起,如何将这些字符串转换为实数,并将它们加在一起? Also assuming that each array in the list could be of different length. 还假设列表中的每个数组可以具有不同的长度。

>>> data = [['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]
>>> sum(float(x[-1]) for x in data)
0.25
sum = 0.
for l in listOfLists:
    sum += float(l[-1])

It should be as simple as: 它应该很简单:

sum(map(float,(lst1[-1],lst2[-1])))

Sample output: 样本输出:

>>> lst1 = ["1", ".1"]
>>> lst2 = ["1", ".2"]
>>> sum(map(float,(lst1[-1],lst2[-1])))
0.30000000000000004

This works - 这有效-

>>> li = [['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]
>>> reduce(lambda x,y:float(x[-1])+float(y[-1]), li)
0.25
as_string = [['1', '1', '1', '1', '1', '.12'], ['1', '1', '1', '1', '1', '.13']]
as_numbers = [map(float, arr) for arr in as_string]
result = sum(arr[-1] for arr in as_numbers)

or just: 要不就:

result = sum(float(arr[-1]) for arr in as_string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM