简体   繁体   English

Python 3.6v range()函数将无法执行

[英]Python 3.6v range() function won't execute

def fn():
  theList = []
  for rev in range(5, 0, -1):
    theList.append(rev)
    print(theList)

fn()

I don't understand, why this won't execute? 我不明白,为什么这样不执行? My goal is to print something like this 我的目标是打印这样的东西

[5,4,3,2,1,0]
[4,3,2,1,0]
[3,2,1,0]
[2,1,0]
[1,0]
[0]

Edit 1. Okey i added the comma(,) but the result is this 编辑1. Okey我添加了逗号(,),但结果是这样

[5]
[5, 4]
[5, 4, 3]
[5, 4, 3, 2]
[5, 4, 3, 2, 1]

Which is not what i am looking for 这不是我想要的

1)There is a typo in your function: 1)您的功能有错别字:

for rev in range(5, 0, -1):

2) you need to use your rev: 2)您需要使用自己的转速:

for rev in range(5, -1, -1):
    print(range(rev,-1,-1))

You can get your output like this: 您可以这样获得输出:

def fn():
    theList = list(range(5, -1, -1))
    for idx in range(len(theList)):
        print(theList[idx:])
fn()

Output: 输出:

[5, 4, 3, 2, 1, 0]
[4, 3, 2, 1, 0]
[3, 2, 1, 0]
[2, 1, 0]
[1, 0]
[0]

Your code is using the wrong approach. 您的代码使用了错误的方法。 Basically, your output shows that the list is full initially and goes on popping one element from the left on each iteration. 基本上,您的输出显示该列表最初是完整的,并在每次迭代中从左侧弹出一个元素。 Your approach starts with an empty list and adds an element on each iteration. 您的方法从一个空列表开始,并在每次迭代中添加一个元素。

Also, range(5, 0, -1) is not the list you think it is. 同样, range(5, 0, -1)也不是您认为的列表。 This is because the range function ignores the end value which is 0 here. 这是因为范围功能会忽略此处为0的最终值。

If you did this list(range(5, 0, -1)) , you'd get [5, 4, 3, 2, 1] which obviously doesn't contain 0. So, to get the list you want, you'd have to do list(range(5, -1, -1)) like in the code above. 如果您执行了此list(range(5, 0, -1)) ,则将得到[5, 4, 3, 2, 1] ,其中显然不包含0。因此,要获取所需的列表,您可以就像上面的代码一样,必须执行list(range(5, -1, -1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM