如何使用循环在 Python 中保存嵌套列表的元素并删除列表

How to save elements of a nested list in Python using a loop and deleting the list

我正在尝试创建一个列表列表(嵌套列表),分别将用户的元素数量和列表数量作为 b、a。但是,如何将 temp_list 保存到 list_of_lists。由于我在将 temp_list 附加到 list_of_list 之后将其删除,因此后面列表中的元素也将被删除。

a, b= map(int,input().split())
i = 0
list_of_lists = []
while i < b:
    temp_list = []
    temp_list.append(map(float, input().split()))
    print(temp_list, i)
    list_of_list.append(temp_list)
    del temp_list[:]
    i += 1

print(list_of_lists)

几个问题:

  • 您不应该 del temp_list[:] 删除刚添加的对象。
  • 您的循环作为 for 循环会更好。
  • 您的变量名为 list_of_lists 而不是 list_of_list,因此 list_of_list.append() 应该抛出一个 NameError
  • map在Py3中returns一个迭代器,所以你需要把它变成一个列表,你可以使用temp_list.extend(map(...))但你可以直接创建它。注意:您对 map(...) 的第一次使用被解压到单个变量中,因此可以按预期工作。

更新代码:

a, b = map(int, input().split())
list_of_lists = []
for i in range(b):
    temp_list = list(map(float, input().split()))
    print(temp_list, i)
    list_of_lists.append(temp_list)

在您的代码中,您每次都会删除临时列表

del temp_list[:]

而不是

a, b = map(int, input().split())

您可以像

一样简单地使用它
a, b = map(int, input()) 

然后输入像3,4这样的输入python会自动得到它作为一个元组并分别赋值给变量a,b

a, b = map(int, input()) #3,4
list_of_lists = []
for i in range(b):
    temp_list = list(map(float, input())) 
    print(temp_list, i)
    list_of_lists.append(temp_list)
print (list_of_lists)