【问题标题】:Python3 - create global variable(list) from functionPython3 - 从函数创建全局变量(列表)
【发布时间】:2016-11-04 13:16:45
【问题描述】:

我有这个代码(示例):

count = 3

def test(count):
    a = 1
    while a <= count:
        global list + str(a)
        list + str(a) = []
        print(a)
        a += 1

test(count)

print(list1)
print(list2)
print(list3)

如何在函数中动态创建全局变量(列表)? 我需要让我的代码正常工作,需要从外部函数访问变量(列表):“list1”、“list2”和“list3”。

谢谢

【问题讨论】:

  • 为什么不能将list1list2list3 放在实际列表中?或者更好的是,dict?
  • 你真的不想这样做。 This 处理你的变量变量,然后只返回字典。
  • 你能给我举个例子吗?
  • @MorganThrapp 所以,我可以使用 1 个全局字典并使用动态键在其上写入一些数据?
  • 是的,我已经做到了。我给你的链接显示了如何制作字典,至于返回,你需要阅读教程。那是 Python 101。

标签: python list python-3.x global-variables


【解决方案1】:

非常感谢大家。 我使用了这段代码:

count = 3
urls = {}

def test(count):
    a = 1
    while a <= count:
        urls[a] = 'test'
        a += 1

test(count)
print(urls)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 2016-10-25
    • 2019-04-04
    相关资源
    最近更新 更多