为什么我不能使用循环在列表中创建列表?

Why can't I create lists within a list using loops?

我有这个代码(房间地图的左墙):

roomMap = []
ones = [1] * 50
for i in ones:
    roomMap = roomMap + [[i]]
    roomMap.append("\n")
print(len(roomMap))
print(roomMap)

它应该在 50 行上打印 50 然后 [1],但它打印 100 然后重复 [1], '\n' 50 次。
为什么会这样?

它打印 100 并重复 [1]、'\n' 50 次,因为您将“\n”附加到 roomMap。

您所做的是将 [1] 和“\n”都附加到列表“roomMap”中。因此,对于每一次迭代,您都将 2 个元素([1] 和“\n”)推送到列表中。列表不是字符串,因此您不需要附加空白字符。

尝试使用:

roomMap = []
ones = [1] * 50
for i in ones:
    roomMap = roomMap + [[i]]
print(len(roomMap))
for i in roomMap:
    print(i)

给你:

roomMap = [1] * 50 # Here, the list is filled with 1
print(len(roomMap))
for i in roomMap:
    print(i)

print() 已经转到下一行。 此打印:

50
1
1
1
1 #etc..

如果你想要列表的列表,只需添加括号

roomMap = [[1]] * 50 #Here, the list is filled with [1]
print(len(roomMap))
for i in roomMap:
    print(i)

这个打印

50
[1]
[1]
[1] #etc..

试试这个

roommap=[]
a=[[1]]*50
for i in a:
    roommap.append(i)
print(len(a))
print(*roommap,sep='\n')