Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个 list a = [1, 2, 3, 4, 5],现在我希望1从以后的每个元素中添加一个index 2,即a[2] + 1, a[3] + 1, a[4] + 1。
a = [1, 2, 3, 4, 5]
1
index 2
a[2] + 1
a[3] + 1
a[4] + 1
那是我a = [1, 2, 4, 5, 6]到底想要的。
a = [1, 2, 4, 5, 6]
什么是最Pythonic的东方式?
>>> a = [1, 2, 3, 4, 5] >>> a[2:] = [x+1 for x in a[2:]] >>> a [1, 2, 4, 5, 6]
对于 numpy 数组:
>>> a = np.array([1,2,3,4,5]) >>> a[2:] += 1 >>> a array([1, 2, 4, 5, 6])
for i in range(2, len(a)) : a[i] += 1