gpt4 book ai didi

python - 如何在Python中追加某个索引的列表?

转载 作者:行者123 更新时间:2023-12-02 09:59:45 24 4
gpt4 key购买 nike

我有一个这样的列表;

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 元素和第 8 元素并在其旁边添加相邻元素而形成的彼此在 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)

但我没有得到所需的输出...实际上 list2 没有更新,我得到:

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

最佳答案

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

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]

关于python - 如何在Python中追加某个索引的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com