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

发布于 2024-12-02 11:01:24 字数 107 浏览 3 评论 0 原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

旧竹 2024-12-09 11:01:24

使用 reversed() 函数(高效,因为 range 实现 __reversed__):

reversed(range(10))

更有意义。

更新: list 转换

如果你希望它是一个列表(正如@btk指出的):

list(reversed(range(10)))

更新:range 解决方案

如果您想仅使用 range 来获得相同的结果,则可以使用其所有参数。 range(start, stop, step)

例如,要生成列表[3, 2, 1, 0],您可以使用以下命令:

range(3, -1, -1)

可能不太直观,但在文本较少的情况下效果相同。 @Wolf 的回答表明这种方法比反转稍快。

Use reversed() function (efficient since range implements __reversed__):

reversed(range(10))

It's much more meaningful.

Update: list cast

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

list(reversed(range(10)))

Update: range-only solution

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

range(3, -1, -1)

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.

爱要勇敢去追 2024-12-09 11:01:24

使用“范围”内置函数。签名是范围(开始、停止、步骤)。这会生成一个产生数字的序列,从 start 开始,并在到达 stop 时结束(不包括 stop)。

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

列表构造函数将范围(这是一个Python生成器)转换为列表。

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)
    range(9, -1, -1)
>>> list(range(9,-1,-1))
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> list(range(-2, 6, 2))
    [-2, 0, 2, 4]

The list constructor converts range (which is a python generator), into a list.

迷爱 2024-12-09 11:01:24

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

You could use range(10)[::-1] which is the same thing as range(9, -1, -1) and arguably more readable (if you're familiar with the common sequence[::-1] Python idiom).

夜司空 2024-12-09 11:01:24

对于那些对迄今为止收集的选项的“效率”感兴趣的人...

Jaime RGP 的回答引导我<强>重新启动我的计算机定时Jason 完全遵循我自己的建议(通过评论)。为了避免您好奇的停机时间,我在这里展示我的结果(最差的在前):[1]

杰森的回答(也许只是对列表理解):

$ 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

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

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


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

肤浅与狂妄 2024-12-09 11:01:24

使用 reverse 没有意义,因为 range 函数可以返回反向列表。

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

  1. 提供stop参数为 -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 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 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]
扎心 2024-12-09 11:01:24
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

留一抹残留的笑 2024-12-09 11:01:24

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

  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.

胡大本事 2024-12-09 11:01:24

除了可读性之外,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 :)

半边脸i 2024-12-09 11:01:24

此问题中的要求需要一个大小为 10 的整数列表,按降序排列
命令。那么,让我们用 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]
画中仙 2024-12-09 11:01:24

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

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

输出将是
[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 ,

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

玩心态 2024-12-09 11:01:24

我相信这会有所帮助,

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 
开始看清了 2024-12-09 11:01:24
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]
笑叹一世浮沉 2024-12-09 11:01:24

不使用 [::-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!")
骑趴 2024-12-09 11:01:24

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

尽管如此,对于这种情况,所有正确的答案仍然完全没问题,我想指出 Wolf 的答案 仅用于生成索引。因此,我为以相反的顺序遍历现有列表制定了类似的基准。

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

注意:如果您想更详细地分析不同的反转方案及其性能,请查看这个很棒的答案

先决条件:

a = list(range(10))

Jason 的答案

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

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)

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

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

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

椵侞 2024-12-09 11:01:24
[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]
猫腻 2024-12-09 11:01:24

因为 range(n) 生成一个可迭代对象,所以您可以做各种各样的好事情来生成您想要的结果,例如:

range(n)[::-1]

如果循环没问题,我们可以创建一个队列:

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

或者也许可以使用它的reverse()方法:

reverse(range(n))

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)[::-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(range(n))
清晰传感 2024-12-09 11:01:24

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

我还不会笑 2024-12-09 11:01:24

假设你有一个列表,称之为
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.

还不是爱你 2024-12-09 11:01:24

您可以使用像这样的用户定义函数:

def range_reversed(start: int, stop: int, step: int) -> range:

# Determine the number of elements in the sequence
num_elem = len(range(start, stop, step))

# Calculate the start of the reverse sequence using the formula for an arithmetic sequence
start_reversed = start + (num_elem - 1) * step

# Determine the stop of the reverse sequence
stop_reversed = start - 1 if step > 0 else start + 1

return range(start_reversed, stop_reversed, -step)
# Example usage:
print(list(range_reversed(0,13,4)))
# Output: [12, 8, 4, 0]

You could use a User-Defined Function like this one:

def range_reversed(start: int, stop: int, step: int) -> range:

# Determine the number of elements in the sequence
num_elem = len(range(start, stop, step))

# Calculate the start of the reverse sequence using the formula for an arithmetic sequence
start_reversed = start + (num_elem - 1) * step

# Determine the stop of the reverse sequence
stop_reversed = start - 1 if step > 0 else start + 1

return range(start_reversed, stop_reversed, -step)
# Example usage:
print(list(range_reversed(0,13,4)))
# Output: [12, 8, 4, 0]
唔猫 2024-12-09 11:01:24
range(9,-1,-1)
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

是正确的形式。如果你使用的话,

reversed(range(10))

你不会得到 0 的情况。例如,假设您的 10 不是一个神奇的数字,并且是您用来从反向开始查找的变量。如果你的 n 情况是 0,reverse(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.

夜巴黎 2024-12-09 11:01:24

获取给定输入整数反转的反向输出。
例子
输入是:5

答案应该是:

54321
1234
321
12
1

答案是:

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)
    

Get the reverse output of reversing the given input integer.
example
input is:5

The answer should be:

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)
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文