在代码为 运行 时创建列表并将它们添加到列表父级

Creating lists while code is running and adding them to an List Parent

我正在尝试根据用户输入给出的值创建列表,然后我想将创建的这些列表添加到父列表中,在父列表中都可以访问和使用它们。

例如,我希望 for 循环获取用户输入的数字,并根据该数字创建编号从 1 到他们选择的任何数字的列表。在每次重复结束时,我想将创建的列表添加到父列表。

这是我目前所知道的,我想我正在努力将它们添加到父列表中。

lists = int(input("How many lists do you want? "))
varname = 'iteration_number_'
parent_list = []

for i in range(lists):
    iteration_number = i+1 #So it does not start from 0
    iteration_names = varname + str(iteration_number) #merging the name and the number

    x = parent_list.append(exec(f"{iteration_names} = []")) #creating lists with that name

try:
    iteration_number_1.append("Cow") # appends Cow to the first list if existing
    iteration_number_2.append("Moo") # appends Moo to the first list if existing

    print(iteration_number_1)
    print(iteration_number_2)

except NameError:
    pass

print(parent_list)
parent_list[0].append("This is list iteration_number_1 but I'm not working")

代码的最后一部分没有按计划运行。当我打印 parent_list 时,在我的脑海中我应该得到 [[iteration_number_1], [iteration_number_2]] 并且可以像这样访问它们

parent_list[0].append("Hello") #appending to the iteration_number_1 list

有谁知道更好的主意吗?或者如何让这个想法发挥作用?

程序员称他们为nested lists:

myNestedList = [
    [1, 2, 3], 
    [4, 5, 6], 
    [7, 8, 9]
]

您可以通过这种方式访问​​内部 lists:

>>> myNestedList[0] # Get the first row
[1, 2, 3]
>>> myNestedList[0][2]
3

您可以通过这种方式将元素附加到内部列表:

>>> myNestedList[0].append(10)
>>> myNestedList
[[1, 2, 3, 10], [4, 5, 6], [7, 8, 9]]

我看到你使用 strings 作为键而不是 integers,这样:

iteration_names = varname + str(iteration_number) #merging the name and the number
x = parent_list.append(exec(f"{iteration_names} = []")) #creating lists with that name

在你的情况下这是个坏主意,但你可以使用 dictionaries,这样:

myDict: dict = {
    "iteration_name_1": <first-element-of-the-list>,
    "iteration_name_2": <second-el...>
}

您可以通过以下方式访问词典:

>>> myDict['iteration_name_1']
<first-element...>

如果您在程序结束时尝试这样做:

parent_list[0].append(iteration_name_1)

它没有用,我建议以这种方式按名称创建列表(如果你真的需要用像 'name_x' 这样的名称来调用它们):

>>> locals()['iteration_name_1'] = []
>>> iteration_name_1
[]

与问题无关,但是...

for i in range(lists):
iteration_number = i+1 #So it does not start from 0

...你应该知道更好的做法是这样做:

for i in range(1, lists):
    # i starts from 1

总之...


最佳做法是这样做:

for i in range(lists):
    parent_list.append([])
try:
    parent_list[0].append('Cow')
    parent_list[1].append('Moo')
except IndexError: # There is a different exception for an element not found in parent_list
    pass

您可以尝试创建一个字典,其中键作为迭代次数的字符串,值作为列表:

d = {}
d["iteration_number_1"] = []
...

d["iteration_number_1"].append("hello")