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

如何range()在Python中生成以下列表?

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

How can you produce the following list with range() in Python?

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

回答 0

使用reversed()功能:

reversed(range(10))

这更有意义。

更新:

如果您希望将其作为列表(如btk所指出):

list(reversed(range(10)))

更新:

如果只想使用range以达到相同的结果,则可以使用其所有参数。range(start, stop, step)

例如,要生成一个list [5,4,3,2,1,0],可以使用以下命令:

range(5, -1, -1)

它可能不那么直观,但是正如评论所提到的那样,这效率更高,并且正确使用范围用于反向列表。

use reversed() function:

reversed(range(10))

It’s much more meaningful.

Update:

If you want it to be a list (as btk pointed out):

list(reversed(range(10)))

Update:

If 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 [5,4,3,2,1,0], you can use the following:

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.


回答 1

使用“范围”内置功能。签名是range(start, stop, step)。这样会产生一个序列,该序列产生的数字以开头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]

在Python 3中,这会产生一个非列表range对象,该对象的作用类似于只读列表(但使用的内存较少,特别是大范围内存)。

Use the ‘range’ built-in function. The signature is range(start, stop, step). This produces a sequence that yields numbers, starting with start, and ending if stop has been reached, excluding 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).


回答 2

您可以使用与Python range(10)[::-1]相同的东西,range(9, -1, -1)并且可以说更具可读性(如果您熟悉通用的sequence[::-1]Python习惯用法)。

You could userange(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).


回答 3

对于那些对迄今收集到的选择的“效率”感兴趣的人…

Jaime RGP的回答使我在按照我自己的建议(通过评论)从字面上看Jason的 “具有挑战性”的解决方案计时重新启动计算机。为了使您免于停机的好奇心,我在这里介绍我的结果(最差优先):

杰森Jason)的答案(也许只是列表理解能力的偏移):

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

martineau的答案(如果您熟悉扩展切片语法,则可以阅读):

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

MichałŠrajer的答案(公认的答案,非常可读):

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

bene的回答(第一个,但当时很粗略):

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

使用Val Neekmanrange(n-1,-1,-1)记法很容易记住最后一个选项。

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):

Jason’s answer (maybe just an excursion into the power of list comprehension):

$ 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):

$ 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):

$ 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.


回答 4

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

将解决这个问题。它将输出8到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


回答 5

没有意义,reverse因为range方法可以返回反向列表。

当您对n个项目进行迭代并且想要替换返回的列表的顺序时,range(start, stop, step)必须使用range的第三个参数来标识step并将其设置为-1,其他参数应相应地进行调整:

  1. 提供一站式参数为-1(这是以前的价值stop - 1stop等于0)。
  2. 作为开始参数使用n-1

因此,等效的range(n)相反:

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

No sense to use reverse because the range method 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 identifies step and set it to -1, other parameters shall be adjusted accordingly:

  1. Provide stop parameter as -1(it’s previous value of stop - 1, stop was equal to 0).
  2. As start parameter use n-1.

So equivalent of range(n) in reverse order would be:

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

回答 6

除了可读性,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

就好像有人在想:)

Readibility aside, reversed(range(n)) seems to be faster than 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 :)


回答 7

此问题中的要求要求list按降序排列大小为10的整数a 。因此,让我们在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]

The requirement in this question calls for a list of integers of size 10 in descending order. So, let’s produce a list in 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]

回答 8

您可以使用range()BIF Like来打印反向数字,

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

输出将是[10,9,8,7,6,5,4,3,2,1]

range()-范围(start,end,increment / decrement),其中start是包含在内的,end是互斥的,而增量可以是任何数字,其行为类似于step

You can do printing of reverse numbers with 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]

range() – range ( start , end , increment/decrement ) where start is inclusive , end is exclusive and increment can be any numbers and behaves like step


回答 9

经常问到的问题是否range(9, -1, -1)reversed(range(10))Python 3 更好?使用迭代器使用其他语言的人会立即想到,reversed()必须缓存所有值,然后以相反的顺序返回。问题是,reversed()如果对象只是一个迭代器,Python的运算符将不起作用。该对象必须具有以下两项之一才能使reversed()起作用:

  1. 支持len()和整数索引通过[]
  2. __reversed__()实施方法。

如果您尝试对以上均不使用的对象使用reversed(),则会得到:

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

简而言之,Python reversed()仅用于类似对象的数组,因此它应具有与正向迭代相同的性能。

但是呢range()?那不是生成器吗?在Python 3中,它是生成器,但包装在同时实现以上两者的类中。因此,range(100000)它不会占用大量内存,但仍支持高效的索引编制和反转。

因此,总而言之,您可以在reversed(range(10))不影响性能的情况下使用它。

Very often asked question is whether range(9, -1, -1) better than reversed(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’s reversed() operator doesn’t work if the object is just an iterator. The object must have one of below two for reversed() to work:

  1. Either support len() and integer indexes via []
  2. Or have __reversed__() method implemented.

If you try to use reversed() on object that has none of above then you will get:

>>> [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.

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. So range(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.


回答 10

我相信这会有所帮助,

range(5)[::-1]

下面是用法:

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

i believe this can help,

range(5)[::-1]

below is Usage:

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

回答 11

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

回答 12

不带[::-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!")

Using without [::-1] or reversed –

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!")

回答 13

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

回答 14

您不一定需要使用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.


回答 15

假设您有一个名为a = {1,2,3,4,5}的列表,现在,如果您要反向打印该列表,则只需使用以下代码。

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

我知道您问使用范围,但它已经回答。

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.reverse
for i in a:
   print(i)

I know you asked using range but its already answered.


回答 16

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

是正确的形式。如果您使用

reversed(range(10))

您不会得到0的情况。例如,假设您的10不是一个神奇的数字,而用于查找的变量是从反向开始的。如果您的n大小写为0,则将不会执行reversed(range(0)),如果您偶然在零索引中包含单个对象,那么将是错误的。

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. 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.


回答 17

我认为,许多人(作为我自己)可能对按反向顺序遍历现有列表的常见情况感兴趣,而不是如标题中所述,而不仅仅是为此类遍历生成索引。

即使对于这种情况,所有正确的答案仍然是完全正确的,但我想指出的是,在Wolf的答案中所做的性能比较仅用于生成索引。因此,我为反向遍历现有列表做了类似的基准测试。

TL; DR a[::-1]是最快的。

先决条件:

a = list(range(10))

杰森的答案

%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的答案

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

MichałŠrajer的答案

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

贝恩的答案

%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)

如您所见,在这种情况下,无需显式生成索引,因此最快的方法是减少额外操作的方法。

注意:我在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.

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:

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

bene’s answer:

%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. It uses standard timeit.timeit under the hood. Tested for Python 3.7.3


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。