英文:
Multiplying by 2 every other element in a list starting from the end of the list
问题
a = [1, 2, 3, 4, 5, 6, 7]
a = [i*2 for i in a[-1::-2]]
print(a)
# 或者
a = [1, 2, 3, 4, 5, 6, 7]
for i in range(len(a) - 1, -1, -2):
a[i] *= 2
英文:
I want to make a list that multiplies its elements by 2 starting from the end with a step of -2. For example:
a = [1, 2, 3, 4, 5, 6, 7]
# I want it to return a = [2, 2, 6, 4, 10, 6, 14]
I had some ideas but nothing I try works. Take a look at my code:
a = [1, 2, 3, 4, 5, 6, 7]
a = [i*2 for i in a[-1::-2]]
print(a)
#or
a = [1, 2, 3, 4, 5, 6, 7]
for i in a[-1::-2]:
i *= 2
#returns only 14, 10, 6, 2
答案1
得分: 1
你几乎有正确的逻辑。循环遍历索引,并将结果重新分配给列表:
a = [1, 2, 3, 4, 5, 6, 7]
for i in range(len(a)-1, -1, -2):
a[i] *= 2
输出:
[2, 2, 6, 4, 10, 6, 14]
英文:
You had almost the correct logic. Loop on the indices an assign back to the list:
a = [1, 2, 3, 4, 5, 6, 7]
for i in range(len(a)-1, -1, -2):
a[i] *= 2
Output:
[2, 2, 6, 4, 10, 6, 14]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论