用 range() 以相反的顺序打印列表?
如何在 Python 中使用 range()
生成以下列表?
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何在 Python 中使用 range()
生成以下列表?
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(21)
使用
reversed()
函数(高效,因为range
实现__reversed__
):更有意义。
更新:
list
转换如果你希望它是一个
列表
(正如@btk指出的):更新:仅
range
解决方案如果您想仅使用
range
来获得相同的结果,则可以使用其所有参数。range(start, stop, step)
例如,要生成列表
[3, 2, 1, 0]
,您可以使用以下命令:可能不太直观,但在文本较少的情况下效果相同。 @Wolf 的回答表明这种方法比
反转
稍快。Use
reversed()
function (efficient sincerange
implements__reversed__
):It's much more meaningful.
Update:
list
castIf you want it to be a
list
(as @btk pointed out):Update:
range
-only solutionIf you want to use only
range
to achieve the same result, you can use all its parameters.range(start, stop, step)
For example, to generate a list
[3, 2, 1, 0]
, you can use the following:It may be less intuitive, but it works the same with less text. This answer by @Wolf indicates this approach is slightly faster than
reversed
.使用“范围”内置函数。签名是
范围(开始、停止、步骤)
。这会生成一个产生数字的序列,从start
开始,并在到达stop
时结束(不包括stop
)。列表构造函数将范围(这是一个Python生成器)转换为列表。
Use the 'range' built-in function. The signature is
range(start, stop, step)
. This produces a sequence that yields numbers, starting withstart
, and ending ifstop
has been reached, excludingstop
.The list constructor converts range (which is a python generator), into a list.
您可以使用
range(10)[::-1]
,它与range(9, -1, -1)
相同,并且可以说更具可读性(如果您熟悉常见的sequence[::-1]
Python 习惯用法)。You could use
range(10)[::-1]
which is the same thing asrange(9, -1, -1)
and arguably more readable (if you're familiar with the commonsequence[::-1]
Python idiom).对于那些对迄今为止收集的选项的“效率”感兴趣的人...
Jaime RGP 的回答引导我<强>重新启动我的计算机定时Jason 完全遵循我自己的建议(通过评论)。为了避免您好奇的停机时间,我在这里展示我的结果(最差的在前):[1]
杰森的回答(也许只是对列表理解):
martineau 的答案(如果您熟悉扩展切片语法):
Michał Šrajer 的答案(已接受的答案,非常可读):
bene 的回答(第一个,但非常粗略当时):
使用
range(n-1,-1,-1),最后一个选项很容易记住)
由 Val Neekman 表示。[1] 正如 Karl Knechtel 所评论的,此处提供的结果与版本相关,并指的是在回答此问题时稳定的 Python 3.x 版本。
For those who are interested in the "efficiency" of the options collected so far...
Jaime RGP's answer led me to restart my computer after timing the somewhat "challenging" solution of Jason literally following my own suggestion (via comment). To spare the curious of you the downtime, I present here my results (worst-first):[1]
Jason's answer (maybe just an excursion into the power of list comprehension):
martineau's answer (readable if you are familiar with the extended slices syntax):
Michał Šrajer's answer (the accepted one, very readable):
bene's answer (the very first, but very sketchy at that time):
The last option is easy to remember using the
range(n-1,-1,-1)
notation by Val Neekman.[1] As commented by Karl Knechtel, the results presented here are version-dependent and refer to the Python 3.x version that was stable at the time of answering this question.
使用
reverse
没有意义,因为range
函数可以返回反向列表。当您迭代 n 个项目并想要替换
range(start, stop, step)
返回的列表顺序时,您必须使用第三个参数 标识step
的范围,并将其设置为-1
,其他参数相应调整:stop
参数为-1
(它是stop 的先前值 - 1
,stop
等于0
)。n-1
作为启动参数。因此,与
range(n)
倒序等效的是:No sense to use
reverse
because therange
function can return reversed list.When you have iteration over n items and want to replace order of list returned by
range(start, stop, step)
you have to use third parameter of range which identifiesstep
and set it to-1
, other parameters shall be adjusted accordingly:stop
parameter as-1
(it's previous value ofstop - 1
,stop
was equal to0
).n-1
.So equivalent of
range(n)
in reverse order would be:将解决这个问题。会输出8比1,-1表示反转列表
will solve this problem. It will output 8 to 1, and -1 means a reversed list
经常被问到的问题是,Python 3 中
range(9, -1, -1)
是否比reversed(range(10))
更好?使用过其他语言的迭代器的人立即倾向于认为reverse()必须缓存所有值,然后以相反的顺序返回。问题是,如果对象只是一个迭代器,Python 的reversed()
运算符将不起作用。该对象必须具有以下两个之一才能使 returned() 工作:len()
并通过[]
进行整数索引,__reversed__() 方法已实现。
如果你尝试在没有上述任何一个的对象上使用reversed(),那么你会得到:
所以简而言之,Python的
reversed()
仅适用于类似数组的对象,因此它应该具有与前向迭代。但是
range()
呢?这不是发电机吗?在 Python 3 中,它是生成器,但包装在一个实现上述两者的类中。所以range(100000)
不会占用大量内存,但它仍然支持高效的索引和反转。总之,您可以使用
reversed(range(10))
而不会影响性能。Very often asked question is whether
range(9, -1, -1)
better thanreversed(range(10))
in Python 3? People who have worked in other languages with iterators immediately tend to think that reversed() must cache all values and then return in reverse order. Thing is that Python'sreversed()
operator doesn't work if the object is just an iterator. The object must have one of below two for reversed() to work:len()
and integer indexes via[]
__reversed__()
method implemented.If you try to use reversed() on object that has none of above then you will get:
So in short, Python's
reversed()
is only meant on array like objects and so it should have same performance as forward iteration.But what about
range()
? Isn't that a generator? In Python 3 it is generator but wrapped in a class that implements both of above. Sorange(100000)
doesn't take up lot of memory but it still supports efficient indexing and reversing.So in summary, you can use
reversed(range(10))
without any hit on performance.除了可读性之外,
reversed(range(n))
似乎比range(n)[::-1]
更快。如果有人想知道的话:)
Readibility aside,
reversed(range(n))
seems to be faster thanrange(n)[::-1]
.Just if anyone was wondering :)
此问题中的要求需要一个大小为 10 的整数列表,按降序排列
命令。那么,让我们用 python 生成一个列表。
The requirement in this question calls for a
list
of integers of size 10 in descendingorder. So, let's produce a list in python.
您可以使用 range() BIF 打印反向数字,
输出将是
[10,9,8,7,6,5,4,3,2,1]
range() - 范围(开始、结束、增量/减量)
其中 start 包含在内,end 包含在内,increment 可以是任意数字,其行为类似于 step
You can do printing of reverse numbers with range() BIF Like ,
Output will be
[10,9,8,7,6,5,4,3,2,1]
range() - range ( start , end , increment/decrement )
where start is inclusive , end is exclusive and increment can be any numbers and behaves like step
我相信这会有所帮助,
以下是用法:
i believe this can help,
below is Usage:
不使用 [::-1] 或反转 -
Using without [::-1] or reversed -
我认为许多人(就像我自己一样)可能对以相反顺序遍历现有列表的常见情况更感兴趣,正如标题中所述,而不仅仅是为此类遍历生成索引。
尽管如此,对于这种情况,所有正确的答案仍然完全没问题,我想指出 Wolf 的答案 仅用于生成索引。因此,我为以相反的顺序遍历现有列表制定了类似的基准。
TL;DR
a[::-1]
是最快的。注意:如果您想更详细地分析不同的反转方案及其性能,请查看这个很棒的答案。
先决条件:
Jason 的答案:
martineau 的 答案答案:
Michał Šrajer 的回答:
bene 的回答:
如您所见,在这种情况下,不需要显式生成索引,因此最快的方法是减少额外操作的方法。
注意:我在 JupyterLab 中进行了测试,它有方便的“魔术命令”
%timeit
。它在底层使用标准的timeit.timeit
。针对 Python 3.7.3 进行了测试I thought that many (as myself) could be more interested in a common case of traversing an existing list in reversed order instead, as it's stated in the title, rather than just generating indices for such traversal.
Even though, all the right answers are still perfectly fine for this case, I want to point out that the performance comparison done in Wolf's answer is for generating indices only. So I've made similar benchmark for traversing an existing list in reversed order.
TL;DR
a[::-1]
is the fastest.NB: If you want more detailed analysis of different reversal alternatives and their performance, check out this great answer.
Prerequisites:
Jason's answer:
martineau's answer:
Michał Šrajer's answer:
bene's answer:
As you see, in this case there's no need to explicitly generate indices, so the fastest method is the one that makes less extra actions.
NB: I tested in JupyterLab which has handy "magic command"
%timeit
. It uses standardtimeit.timeit
under the hood. Tested for Python 3.7.3因为
range(n)
生成一个可迭代对象,所以您可以做各种各样的好事情来生成您想要的结果,例如:如果循环没问题,我们可以创建一个队列:
或者也许可以使用它的reverse()方法:
because
range(n)
produces an iterable there are all sorts of nice things you can do which will produce the result you desire, such as:if loops are ok, we can make sort of a queue:
or maybe use the reverse() method on it:
您不一定需要使用 range 函数,您可以简单地执行 list[::-1] ,它应该快速以相反的顺序返回列表,而不使用任何添加。
You don't necessarily need to use the range function, you can simply do list[::-1] which should return the list in reversed order swiftly, without using any additions.
假设你有一个列表,称之为
a={1,2,3,4,5}
现在,如果您想反向打印列表,则只需使用以下代码即可。
我知道您问过使用范围,但它已经得到了回答。
Suppose you have a list call it
a={1,2,3,4,5}
Now if you want to print the list in reverse then simply use the following code.
I know you asked using range but its already answered.
您可以使用像这样的用户定义函数:
You could use a User-Defined Function like this one:
是正确的形式。如果你使用的话,
你不会得到 0 的情况。例如,假设您的 10 不是一个神奇的数字,并且是您用来从反向开始查找的变量。如果你的 n 情况是 0,reverse(range(0)) 将不会执行,如果你偶然在零索引中有一个对象,这是错误的。
Is the correct form. If you use
you wont get a 0 case. For instance, say your 10 isn't a magic number and a variable you're using to lookup start from reverse. If your n case is 0, reversed(range(0)) will not execute which is wrong if you by chance have a single object in the zero index.
获取给定输入整数反转的反向输出。
例子
输入是:5
答案应该是:
答案是:
Get the reverse output of reversing the given input integer.
example
input is:5
The answer should be:
Answer is: