首页 > 解决方案 > 在循环中将多个变量定义为空列表

问题描述

我正在尝试创建和分配 10 个变量,仅通过它们的索引来区分,所有这些变量都是for循环中的空列表。

理想的输出将是agent_1 = [], agent_2 = [], agent_n = []

我知道我可以全部写出来,但我认为我应该能够创建一个简单的循环。主要问题是在每次迭代中分配空列表

for i in range(1,10):
    agent_ + i = []

标签: pythonpython-3.x

解决方案


为什么不使用键等于 agent_i 的 dict 对象。

dic = {}
for i in range(1,10):
    dic["agent_" + str(i)] = []

// access the dic directly and iterating purpose also just iterate through the dictionary.
print dic["agent_1"]
# iteration over the dictionary
for key,value in dic.items():
    print key,value

这是代码片段的链接


推荐阅读