简体   繁体   中英

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:

  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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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