如何在Python中为某些索引追加列表?

如何在Python中为某些索引追加列表?,python,python-3.x,list,numpy,Python,Python 3.x,List,Numpy,我有一个这样的清单 list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1] # list of 9 elements 我想再有一张这样的list2 list2 = [1, 2, 2, 2, 2, 2, 2, 2, 2, 1] # list of 10 elements list2是通过保留list1中的0th元素和8th元素,并在list1中添加相邻元素而形成的。 这就是我所做的 list2 = [None] * 10 list2[0] = list2[9] = 1 for

我有一个这样的清单

list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1] # list of 9 elements
我想再有一张这样的
list2

list2 = [1, 2, 2, 2, 2, 2, 2, 2, 2, 1] # list of 10 elements
list2
是通过保留
list1
中的
0th
元素和
8th
元素,并在
list1
中添加相邻元素而形成的。 这就是我所做的

list2 = [None] * 10
list2[0] = list2[9] = 1

for idx, i in enumerate(list1):
    try:
        add = list1[idx] + list1[idx+1]
        #print(add) 
        list2[1:9].append(add)
    except:
        pass

print(list2)
但是我没有得到想要的输出。。。实际上列表2没有更新,我得到:

[1, None, None, None, None, None, None, None, None, 1]

比如说:

list2 = list1[:1] + [x + y for x, y in zip(list1[0:], list1[1:])] + list1[-1:]

实现所需结果的另一种方法是有效地移动
list1
,方法是在列表前面加上一个条目0,然后将其添加到自身(通过条目0进行扩展以匹配长度),方法是使用创建一个元组列表,该列表可以迭代:

list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1]

list2 = [x + y for x, y in zip([0] + list1, list1 + [0])]
print(list2)
输出

[1, 2, 2, 2, 2, 2, 2, 2, 2, 1]

与其他答案类似,但我会使用两行代码,使用中间列表(或者如果不再需要,只修改原始列表),以使填充更易于查看:

list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1]

lyst = [0, *list1, 0]
list2 = [prev + cur for prev, cur in zip(lyst, lyst[1:])]

print(list2)

list2[1:9]。append(add)
创建一个新列表,然后将其追加,然后立即丢弃该新列表。您经常这样做吗?性能重要吗?是的@Tim Richardson。如果OP比Python新,它们可能比Python更高,那么对于其他人来说,这可能不太可读them@aws_apprentice也许,但考虑到被接受的、投票最多的答案基本上与这个答案相同,我认为这是可以的。