Python 可以在循环中自动创建一个新数组(并附加到它)吗?

Can Python Automatically Create a New Array (and Append to It) within a Loop?

Python 能否在循环中自动创建一个新数组并向其添加新信息?这只是一个学习目的的问题。

例如,我正在尝试编写一个程序,将信息附加到名为 record001 的数组中。然后经过一些步骤,想要将新信息附加到新数组,但在循环中自动创建该变量名?这可能吗?我在下面给出了一个例子:

counter = 0
record001 = []
    while (counter > -1):

        user_id = input("Enter your 5-digit ID: ")
        record001.append(user_id)

        yob = int(input("Enter your 4-digit year of birth: "))
        record001.append(yob)

        counter += 1
            print("Information Appended to Record #: " + str(counter))
            print(record001)

else:
     print("Program terminated")

谢谢

你不能轻易地完成你所要求的,但是你可以有一个二维记录数组,例如:

>>> records = []
>>> for i in range(10):
...     record = []
...     records.append(record)
...     record.append(i)
...     record.append(i ** 2)
... 
>>> records
[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Patrick 关于使用多维数组的建议非常适合我的尝试。我假设我的问题的理论部分的总体答案——变量名称本身是否可以被操纵——是否定的。

这是使用多维数组的程序(由 Patrick 友情推荐)

counter = 0
records = []

while (counter > -1):
    record = []
    user_id = input("Enter your 5-digit ID: ")
    record.append(user_id)

    yob = int(input("Enter your 4-digit year of birth: "))
    record.append(yob)
    records.append(record)

    counter += 1
    print("Information Appended to Record #: " + str(counter))
    print(records)

else:
    print("Program terminated")