Python: 如何根据用户输入声明全局零数组?

2024-04-26 22:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的程序,用户可以输入一个特定的n

根据这个n,我需要创建一个具有n个大小为零的bucket的全局数组,因为我需要在其他函数中使用这个数组+增加bucket中的元素,这同样取决于某些条件。你知道吗

inv = []   # global var counts all inversion at level n
order = [] # global var counts all ordered elements at level n

def foo():
    # Using order and inv here 

def main():
    # Save Input in variable in n
    n = int(raw_input())
    order = [0]*n
    inv = [0]*n

我该怎么做?我总是收到一个索引器告诉我列表索引超出范围。谢谢!你知道吗


Tags: 用户in程序bucketvardeforder数组
1条回答
网友
1楼 · 发布于 2024-04-26 22:51:48

有两种方法可以做到这一点-全局和参数。你知道吗

使用global关键字可以访问函数中orderinv的全局实例。你知道吗

inv = []   # global var counts all inversion at level n
order = [] # global var counts all ordered elements at level n

def foo():
  # Using order and inv here
  global order
  global inv


def main():
  global order
  global inv
  # Save Input in variable in n
  n = map(int, raw_input().split())
  order = [0]*n
  inv = [0]*n

我建议这样做的方法是在主函数中声明orderinv,然后将它们作为参数传递给foo()或任何其他需要它们的函数。你知道吗

def foo(list_order, list_inv):
  # Using order and inv here

def main():
  # Save Input in variable in n
  n = map(int, raw_input().split())
  order = [0]*n
  inv = [0]*n
  foo(order, inv)

相关问题 更多 >