What is the meaning of reverse=[i]+reverse

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

What is the meaning of reverse=[i]+reverse

问题

reverse = [i] + reverse 这行代码的意思是将当前迭代的元素 i 放在已经反转部分的列表 reverse 的前面。它实际上是在逐步地构建一个反转后的列表。这是一种逐步反转列表的方法,不使用任何内置函数或方法。

英文:

I'm writing code in python to reverse a string and stumble upon this code.

lst = [21,2,3,1,96,55,66,12,19]

reverse = []

for i in lst:
    print([i])
    reverse = [i] + reverse

Wants to know what is the meaning of reverse=[i]+reverse, what does it do ?

I'm trying to reverse a list without using any function or built in methods.
I was thinking of something simple which doesn't involve any functions.

答案1

得分: 2

  1. [i] 只是一个包含一个元素 i 的列表字面值。
  2. 在此之上调用 + reverse,以生成一个新列表,该列表以 i 开始,并以来自 reverse 列表的所有元素结尾。
  3. 最后,reverse 被重新赋值以指向这个新列表。

实际上,这是逐个元素地构建反转列表。

英文:
  1. [i] is just a list literal containing one element, i.
  2. + reverse is called on that, to produce a new list that starts with i, and
    ends with all the elements from the reverse list.
  3. Finally, reverse is re-assigned to point to this new list.

In effect, this is building up the reversed list one element at a time.

huangapple
  • 本文由 发表于 2023年8月10日 11:58:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872571.html
匿名

发表评论

匿名网友

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

确定