简体   繁体   中英

python sum right and left components in list

I have a list:

key: [[1, 3, 4, 5, 3]]

I need to get list like

key: [[6, 5, 8, 7, 6]]

How can I do that with Python?

A simple approach:

>>> my_list = [1, 3, 4, 5, 3]
>>> new_list = []    
>>> for i,x in enumerate(my_list):
...     if i==0:
...         new_list.append(my_list[-1] + my_list[i+1])
...     elif i==len(my_list)-1:
...         new_list.append(my_list[0] + my_list[i-1])
...     else:
...         new_list.append(my_list[i-1] + my_list[i+1])
... 
>>> new_list
... [6, 5, 8, 7, 6]

you could use list comprehension:

[a[i-1]+(a+a[:1])[i+1] for i in range(len(a))]

this works because:

  • a[-1] returns the last element of the list
  • a+a[:1] appends the first element of the list to the end

A functional approach:

from operator import add

list(map(add, key[1:]+key[:1], key[-1:] + key[:-1]))
# [6, 5, 8, 7, 6]

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