简体   繁体   English

使用 range() 以相反的顺序打印列表?

[英]Print a list in reverse order with range()?

How can you produce the following list with range() in Python?你如何在 Python 中使用range()生成以下列表?

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

use reversed() function:使用reversed()函数:

reversed(range(10))

It's much more meaningful.它更有意义。

Update:更新:

If you want it to be a list (as btk pointed out):如果您希望它是一个列表(如 btk 所指出的):

list(reversed(range(10)))

Update:更新:

If you want to use only range to achieve the same result, you can use all its parameters.如果只想使用range来达到相同的结果,则可以使用其所有参数。 range(start, stop, step)

For example, to generate a list [5,4,3,2,1,0] , you can use the following:例如,要生成列表[5,4,3,2,1,0] ,您可以使用以下内容:

range(5, -1, -1)

It may be less intuitive but as the comments mention, this is more efficient and the right usage of range for reversed list.它可能不太直观,但正如评论中提到的,这更有效,并且可以正确使用反向列表的范围。

Use the 'range' built-in function.使用“范围”内置函数。 The signature is range(start, stop, step) .签名是range(start, stop, step) This produces a sequence that yields numbers, starting with start , and ending if stop has been reached, excluding stop .这将产生一个序列,该序列产生数字,从start ,如果到达stop则结束,但不包括stop

>>> range(9,-1,-1)   
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(-2, 6, 2)
    [-2, 0, 2, 4]

In Python 3, this produces a non-list range object, which functions effectively like a read-only list (but uses way less memory, particularly for large ranges).在 Python 3 中,这会产生一个非列表range对象,它的功能类似于只读列表(但使用更少的内存,特别是对于大范围)。

您可以使用range(10)[::-1] ,它与range(9, -1, -1)并且可以说更具可读性(如果您熟悉公共sequence[::-1] Python成语)。

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). Jaime RGP 的回答让我在按照我自己的建议(通过评论)对Jason有点“具有挑战性”的解决方案进行计时重新启动了我的计算机 To spare the curious of you the downtime, I present here my results (worst-first):为了免除您对停机时间的好奇,我在此展示我的结果(最差优先):

Jason's answer (maybe just an excursion into the power of list comprehension ): Jason 的回答(也许只是对列表理解的力量的一次探索):

$ python -m timeit "[9-i for i in range(10)]"
1000000 loops, best of 3: 1.54 usec per loop

martineau's answer (readable if you are familiar with the extended slices syntax ):马蒂诺的回答(如果您熟悉扩展切片语法,则可以阅读):

$ python -m timeit "range(10)[::-1]"
1000000 loops, best of 3: 0.743 usec per loop

Michał Šrajer's answer (the accepted one, very readable): Michał Šrajer 的回答(公认的,非常易读):

$ python -m timeit "reversed(range(10))"
1000000 loops, best of 3: 0.538 usec per loop

bene's answer (the very first, but very sketchy at that time ): bene 的回答(第一个,但当时非常粗略):

$ python -m timeit "range(9,-1,-1)"
1000000 loops, best of 3: 0.401 usec per loop

The last option is easy to remember using the range(n-1,-1,-1) notation by Val Neekman .最后一个选项使用Val Neekmanrange(n-1,-1,-1)表示法很容易记住。

for i in range(8, 0, -1)

will solve this problem.将解决这个问题。 It will output 8 to 1, and -1 means a reversed list它将输出 8 比 1,-1 表示反向列表

No sense to use reverse because the range function can return reversed list.使用reverse没有意义,因为range函数可以返回反向列表。

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 identifies step and set it to -1 , other parameters shall be adjusted accordingly:当您对n项进行迭代并想要替换range(start, stop, step)返回的列表顺序range(start, stop, step)您必须使用 range 的第三个参数来标识step并将其设置为-1 ,其他参数应相应调整:

  1. Provide stop parameter as -1 (it's previous value of stop - 1 , stop was equal to 0 ).提供stop参数为-1 (它是stop - 1的先前值, stop等于0 )。
  2. As start parameter use n-1 .作为开始参数使用n-1

So equivalent of range(n) in reverse order would be:因此,以相反顺序等效于range(n)将是:

n = 10
print range(n-1,-1,-1) 
#[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Readibility aside, reversed(range(n)) seems to be faster than range(n)[::-1] .撇开可读性不谈, reversed(range(n))似乎比range(n)[::-1]快。

$ python -m timeit "reversed(range(1000000000))"
1000000 loops, best of 3: 0.598 usec per loop
$ python -m timeit "range(1000000000)[::-1]"
1000000 loops, best of 3: 0.945 usec per loop

Just if anyone was wondering :)只是如果有人想知道:)

Very often asked question is whether range(9, -1, -1) better than reversed(range(10)) in Python 3?经常被问到的问题是range(9, -1, -1)在 Python 3 中range(9, -1, -1)是否比reversed(range(10))更好? 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.使用迭代器在其他语言中工作过的人立即倾向于认为 reversed() 必须缓存所有值,然后以相反的顺序返回。 Thing is that Python's reversed() operator doesn't work if the object is just an iterator.问题是,如果对象只是一个迭代器,那么 Python 的reversed()运算符就不起作用。 The object must have one of below two for reversed() to work:该对象必须具有以下两个之一才能使 reversed() 工作:

  1. Either support len() and integer indexes via []通过[]支持len()和整数索引
  2. Or have __reversed__() method implemented.或者实现了__reversed__()方法。

If you try to use reversed() on object that has none of above then you will get:如果您尝试在没有上述任何内容的对象上使用 reversed() ,那么您将获得:

>>> [reversed((x for x in range(10)))]
TypeError: 'generator' object is not reversible

So in short, Python's reversed() is only meant on array like objects and so it should have same performance as forward iteration.简而言之,Python 的reversed()仅适用于类似对象的数组,因此它应该具有与前向迭代相同的性能。

But what about range() ?但是range()呢? Isn't that a generator?不是发电机吗? In Python 3 it is generator but wrapped in a class that implements both of above.在 Python 3 中,它是生成器,但包装在一个实现上述两个的类中。 So range(100000) doesn't take up lot of memory but it still supports efficient indexing and reversing.所以range(100000)不会占用大量内存,但它仍然支持高效的索引和反转。

So in summary, you can use reversed(range(10)) without any hit on performance.所以总而言之,您可以使用reversed(range(10))而不会影响性能。

The requirement in this question calls for a list of integers of size 10 in descending order.此问题中的要求要求按降序排列大小为 10 的整数list So, let's produce a list in python.所以,让我们在 python 中生成一个列表。

# This meets the requirement.
# But it is a bit harder to wrap one's head around this. right?
>>> range(10-1, -1, -1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# let's find something that is a bit more self-explanatory. Sounds good?
# ----------------------------------------------------

# This returns a list in ascending order.
# Opposite of what the requirement called for.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# This returns an iterator in descending order.
# Doesn't meet the requirement as it is not a list.
>>> reversed(range(10))
<listreverseiterator object at 0x10e14e090>

# This returns a list in descending order and meets the requirement
>>> list(reversed(range(10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

You can do printing of reverse numbers with range() BIF Like ,您可以使用 range() BIF Like 打印反向数字,

for number in range ( 10 , 0 , -1 ) :
    print ( number ) 

Output will be [10,9,8,7,6,5,4,3,2,1]输出将为 [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 range() - 范围(开始、结束、增量/减量),其中开始是包含的,结束是不包括的,增量可以是任何数字,其行为类似于步骤

range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Using without [::-1] or reversed -不使用 [::-1] 或反向使用 -

def reverse(text):
    result = []
    for index in range(len(text)-1,-1,-1):
        c = text[index]
        result.append(c)
    return ''.join(result)

print reverse("python!")

i believe this can help,我相信这会有所帮助,

range(5)[::-1]

below is Usage:下面是用法:

for i in range(5)[::-1]:
    print i 

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.尽管如此,对于这种情况,所有正确的答案仍然非常好,我想指出Wolf 的答案中所做的性能比较仅用于生成索引。 So I've made similar benchmark for traversing an existing list in reversed order.所以我为以相反的顺序遍历现有列表做了类似的基准测试。

TL;DR a[::-1] is the fastest. TL;DR a[::-1]是最快的。

NB: If you want more detailed analysis of different reversal alternatives and their performance, check out this great answer .注意:如果您想更详细地分析不同的逆转选择及其表现,请查看这个很棒的答案

Prerequisites:先决条件:

a = list(range(10))

Jason's answer :杰森的回答

%timeit [a[9-i] for i in range(10)]
1.27 µs ± 61.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

martineau's answer :马蒂诺的回答

%timeit a[::-1]
135 ns ± 4.07 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Michał Šrajer's answer : Michał Šrajer 的回答

%timeit list(reversed(a))
374 ns ± 9.87 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

bene's answer : bene 的回答

%timeit [a[i] for i in range(9, -1, -1)]
1.09 µs ± 11.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

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 .注意:我在 JupyterLab 中进行了测试,它具有方便的“魔法命令” %timeit It uses standard timeit.timeit under the hood.它在引擎盖下使用标准timeit.timeit Tested for Python 3.7.3已针对 Python 3.7.3 进行测试

[9-i for i in range(10)]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

您不一定需要使用 range 函数,您可以简单地执行 list[::-1] ,它应该以相反的顺序迅速返回列表,而不使用任何添加。

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.假设您有一个列表,将其命名为 a={1,2,3,4,5} 现在,如果您想反向打印列表,只需使用以下代码即可。

a.reverse
for i in a:
   print(i)

I know you asked using range but its already answered.我知道你问使用范围,但它已经回答了。

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:因为range(n)产生一个可迭代的,所以你可以做各种各样的好事情来产生你想要的结果,例如:

range(n)[::-1]

if loops are ok, we can make sort of a queue:如果循环没问题,我们可以创建一个队列:

a = []
for i in range(n):
    a.insert(0,a)
return a

or maybe use the reverse() method on it:或者在其上使用 reverse() 方法:

reverse(range(n))
range(9,-1,-1)
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Is the correct form.是正确的形式。 If you use如果你使用

reversed(range(10))

you wont get a 0 case.你不会得到 0 案例。 For instance, say your 10 isn't a magic number and a variable you're using to lookup start from reverse.例如,假设您的 10 不是一个幻数,而是您用来从反向开始查找的变量。 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.如果您的 n case 为 0,则 reversed(range(0)) 将不会执行,如果您碰巧在零索引中有一个对象,这是错误的。

Get the reverse output of reversing the given input integer. example input 5 The answer should be得到反转给定输入 integer 的反转 output。示例输入 5 答案应该是

54321
1234
321
12
1

Answer is:答案是:

def get_val(n):
    d = ''.join(str(i) for i in range(n, 0, -1))
    print(d)
    print(d[::-1][:-1])
    if n - 1>1:
        return get_vale(n-1)
    
    
get_val(12)
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM