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

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

当前回答

这个问题中的需求需要一个降序为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]

其他回答

range(9,-1,-1)
[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]

我相信这有帮助,

range(5)[::-1]

用法如下:

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

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

假设你有一个列表,叫它 a = {1, 2, 3, 4, 5} 现在,如果你想反向打印列表,那么只需使用下面的代码。

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

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