在python中将列表添加到另一个列表中
我试图做一个循环,不断地将列表添加到另一个列表中在python中将列表添加到另一个列表中,python,loops,Python,Loops,我试图做一个循环,不断地将列表添加到另一个列表中 list1 = [[1], [2], [3], [4]] list2 = [] while True: list2.insert(len(list2), int(input("Here: "))) list1.insert(len(list1), list2) print(list1) list2.clear() 但它给了我这个: Here: 10 [[1], [2], [3], [4],
list1 = [[1], [2], [3], [4]]
list2 = []
while True:
list2.insert(len(list2), int(input("Here: ")))
list1.insert(len(list1), list2)
print(list1)
list2.clear()
但它给了我这个:
Here: 10
[[1], [2], [3], [4], [10]]
Here: 20
[[1], [2], [3], [4], [20], [20]]
Here: 30
[[1], [2], [3], [4], [30], [30], [30]]
Here:
但我想:
Here: 10
[[1], [2], [3], [4], [10]]
Here: 20
[[1], [2], [3], [4], [10], [20]]
Here: 30
[[1], [2], [3], [4], [10], [20], [30]]
Here:
我仍处于基本级别…list1.insert(len(list1),list2)
将相同的对象添加到循环中的list1
。您需要在循环内创建一个新对象。只需在循环中移动list2=[]
[从的复制]list1。插入(len(list1),list2)
将相同的对象添加到循环中的list1
。您需要在循环内创建一个新对象。只需在循环中移动list2=[]
[从的复制]list1.append([int(input)(“Here:”)])
如果使用list.append()
,它总是添加到列表的末尾,这通常是您在这两种情况下所做的
如评论所示,没有必要创建第二个列表。通过将input()
放入[]
-大括号中,可以直接创建列表列表。list1.append([int(input)(“Here:”)]))
如果使用list.append()
,它总是添加到列表的末尾,这通常是您在这两种情况下所做的
如评论所示,没有必要创建第二个列表。您可以通过将input()
放入[]
-大括号中直接创建列表列表。list1.insert(len(list1),list2)
将相同的对象添加到循环内的list1
。您需要在循环内创建一个新对象。只需将list2=[]
移动到循环中list1。插入(len(list1),list2)
将相同的对象添加到循环中的list1
。您需要在循环内创建一个新对象。只需在循环中移动list2=[]