【问题标题】:python3: Why iis the for loop in __init__ method not executed?python3:为什么__init__方法中的for循环没有执行?
【发布时间】:2020-08-12 03:57:15
【问题描述】:
class Field(object):                                                                                                                                                                                               
                                                                                                                                                                                                                   
    def __init__(self, states):                                                                                                                                                                                    
        self.states = states
        states = list(reversed(states))
        self.cells = {}
        print('debug1')
        for y in range(3, 0):
            for x in (1, 4):
                self.cells[(x, y)] = states.pop()
                print(self.cells[(x, y)])
                print('debug2')

my_field = Field('_XXOO_OX_')
print(my_field.cells)

输出是

调试1

{}

但我希望 dict my_field.cells 不为空,并且应该打印出“debug2”。 __init__ 中的 for 循环似乎没有被执行。

Python 版本:3.7.3

【问题讨论】:

  • for y in range(3, 0): 不会像您认为的那样做。当 range 被赋予 2 个参数时,第一个是迭代的开始,第二个是迭代的结束。
  • for y in range(3, 0, -1)替换for y in range(3, 0)
  • 从 2 到 0 你需要range(2, -1, -1)
  • print(list(range(3, 0))) => []

标签: python python-3.x


【解决方案1】:

在从较大的数字迭代到较小的数字时,您需要给出一个步骤:

class Field(object):                                                                                                                                                                                               

    def __init__(self, states):                                                                                                                                                                                    
        self.states = states
        states = list(reversed(states))
        self.cells = {}
        print('debug1')
        for y in range(3, 0, -1):          # Here add -1 in your for loop range
            for x in (1, 4):
                self.cells[(x, y)] = states.pop()
                print(self.cells[(x, y)])
                print('debug2')

my_field = Field('_XXOO_OX_')
print(my_field.cells)

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2016-01-10
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    相关资源
    最近更新 更多