乘以2,从列表末尾开始,每隔一个元素。

huangapple go评论58阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2023年5月11日 19:18:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76227047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定