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

我正在尝试创建一个列表列表(嵌套列表),分别将元素的数量和用户列表的数量分别定为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)


翻翻过去那场雪
浏览 132回答 2
2回答

神不在的星期二

几个问题:您不应该del temp_list[:]删除刚刚添加的对象。您的循环会更好for。您的变量称为list_of_listsnot&nbsp;list_of_list,因此list_of_list.append()应抛出一个NameErrormap在Py3中,它会返回一个迭代器,因此您需要将其转换为列表,可以使用,temp_list.extend(map(...))但可以直接创建它。注意:的首次使用map(...)已解压缩到各个变量中,因此可以按预期工作。更新的代码:a, b = map(int, input().split())list_of_lists = []for i in range(b):&nbsp; &nbsp; temp_list = list(map(float, input().split()))&nbsp; &nbsp; print(temp_list, i)&nbsp; &nbsp; list_of_lists.append(temp_list)

收到一只叮咚

在您的代码中,您每次都删除临时列表del temp_list[:]代替a, b = map(int, input().split())您可以像这样简单地使用它a, b = map(int, input())&nbsp;并输入3,4之类的输入python将自动将其作为元组获取,并将其分别分配给变量a,ba, b = map(int, input()) #3,4list_of_lists = []for i in range(b):&nbsp; &nbsp; temp_list = list(map(float, input()))&nbsp;&nbsp; &nbsp; print(temp_list, i)&nbsp; &nbsp; list_of_lists.append(temp_list)print (list_of_lists)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python