如何在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(n)生成了一个可迭代对象,所以你可以做各种各样的事情来产生你想要的结果,比如:

range(n)[::-1]

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

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

或者可以使用reverse()方法:

reverse(range(n))

这个问题中的需求需要一个降序为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]
[9-i for i in range(10)]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

你可以用range() BIF打印反向数字,比如,

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

输出将是 (10、9、8、7、6、5、4、3、2、1]

Range() -范围(开始,结束,递增/递减) 哪里开始是包括,结束是排他和增量可以是任何数字和行为像步骤

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