【发布时间】:2020-01-06 23:23:50
【问题描述】:
我有一个这样的清单;
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 是通过将0th 元素和8th 元素与list1 保持并在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]
【问题讨论】:
-
list2[1:9].append(add)创建一个新列表,然后附加到它,然后立即丢弃该新列表。 -
你经常这样做吗?性能很重要吗?
-
是的@蒂姆·理查森。
标签: python python-3.x list numpy