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

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

其他回答

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

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

我相信这有帮助,

range(5)[::-1]

用法如下:

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

这个问题中的需求需要一个降序为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(10)[::-1],它和range(9, -1, -1)是一样的,而且可以说可读性更强(如果你熟悉常见的序列[::-1]Python习语)。