python方法破坏了代码


明月清风上善若水自由如风
2025-03-17 01:38:36 (1月前)


我写了一些代码,我想转换成我可以导入的东西,而不是它被用作主要的。

floorMap = [[000,000,000,000,000,999,999,999,999,999],
[000000999000,…

2 条回复
  1. 0# 解天 | 2019-08-31 10-32



    特别是你的问题来自你的全局变量

    currentNum

    。这基本上就是你在做的事情:




    1. current = 0

    2. def f():
      current = 1
      g()

    3. def g():
      print(current)

    4. f() # Output: 0

    5. </code>


    你需要做的是:




    1. current = 0

    2. def f():
      global current
      current = 1
      g()

    3. def g():
      print(current)

    4. f() # Output: 1

    5. </code>


    或更好 :




    1. def f():
      current = 1
      g(current)

    2. def g(current):
      print(current)

    3. f() # Output: 1

    4. </code>


    此外,你应该考虑使用更pythonic synthax为您的

    calcMap

    功能,如:




    1. def calc_map():
      while floor_map[robot_x][robot_y] == uncalculated :
      for x,array in enumerate(floor_map):
      for y,element in enumerate(array):
      if uncalculated < element < wall:
      current_num = element + 1
      change_surroundings(x, y, current_num)

    2. </code>

登录 后才能参与评论