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

标签 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 元素和第 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/

相关文章:

Python 3.4 - Pandas - 帮助正确排列数据框列和删除无效列

r - 如何按 R 列表中的唯一值进行分组

Python Selenium - 属性错误 : WebElement object has no attribute sendKeys

python - 何时以及为何 socket.send() 在 python 中返回 0?

python-3.x - 需要没有复选标记且平坦边框的复选按钮

python - 如何在 Python 中按元素加入列表?

python - 如何对包含空列表的列表进行垂直平均?

python - 如何使用多个分隔符拆分 python 字符串?

python - 随机样本和 "selection order"

python - 使用 Qsettings 恢复 QCheckBox