[英]How to append the list in Python for certain index?
我有一个这样的清单;
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
的8th
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)
但我没有得到所需的输出......实际上 list2 没有更新,我得到:
[1, None, None, None, None, None, None, None, None, 1]
实现所需结果的另一种方法是有效地移动list1
,方法是在列表中添加一个条目为 0 的列表,然后将其添加到自身(通过条目 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]
与其他答案类似,但我会使用中间列表在两行代码中完成(或者,如果您不再需要它,只需修改原始列表)以使填充更容易看到:
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 = list1[:1] + [x + y for x, y in zip(list1[0:], list1[1:])] + list1[-1:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.