简体   繁体   English

根据其他元素对列表列表的最后一个元素求和?

[英]Summing the last elements of the list of lists based on other elements?

I have two lists as follows:我有两个列表如下:

 lst1=[[1,1,2],[1,2,4],[2,1,7],[2,2,10]]
 lst2=[[1,1,0.2],[1,2,0.4],[2,1,0.7],[2,2,0.5]]

I would like to sum the last elements of the above lists, where the first two elements of the items are identical.我想对上述列表的最后一个元素求和,其中项目的前两个元素是相同的。 So my desired output should be:所以我想要的输出应该是:

  output=[[1,1,2.2],[1,2,4.4],[2,1,7.7],[2,2,10.5]]

I am a bit new in python, and tried the below code:我对python有点陌生,并尝试了以下代码:

  ziplst = zip(lst1, lst2)
  sum = [x + y for (x, y) in ziplst]

but it gives me this output, which is not correct:但它给了我这个输出,这是不正确的:

   sum=
   [[1, 1, 2, 1, 1, 0.2], [1, 2, 4, 1, 2, 0.4], [2, 1, 7, 2, 1, 0.7], [2, 2, 10, 2, 2, 
   0.5]]

Following your list comprehension approach you can use this,按照您的列表理解方法,您可以使用它,

# To have a skipped case
#lst1=[[1,1,2],[1,2,4],[2,0,7],[2,2,10]]

# Original
lst1=[[1,1,2],[1,2,4],[2,1,7],[2,2,10]]
lst2=[[1,1,0.2],[1,2,0.4],[2,1,0.7],[2,2,0.5]]

output = [[x[0], x[1], x[2] + y[2]] for x,y in zip(lst1, lst2) if x[:2] == y[:2]]

print(output)

In your answer, you were correctly looping through both lists with zip , but then you were adding these two lists together (merging), instead of adding up only the values of the last element.在您的回答中,您正确地使用zip遍历了两个列表,但是随后您将这两个列表添加到了一起(合并),而不是仅将最后一个元素的值相加。 You were also missing the condition that checks if first two values are equal.您还缺少检查前两个值是否相等的条件。

Note the commented out list with an entry that would be skipped.请注意带有将被跳过的条目的注释掉列表。 For debugging purposes it's definitely better than one where all entries are added.出于调试目的,它绝对比添加所有条目的方法要好。

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

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