简体   繁体   English

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

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

I have this code (For the left wall of roomMap):我有这段代码(对于 roomMap 的左墙):

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

It is supposed to print 50 then [1] on 50 lines, but it prints 100 then repeats [1], '\n' 50 times.它应该在 50 行上打印50然后[1] ,但它打印100然后重复[1], '\n' 50 次。
Why is this happenning?为什么会这样?

It prints 100 and repeats [1], '\n' 50 times because you append the "\n" to the roomMap.它打印 100 并重复 [1], '\n' 50 次,因为您 append 将 "\n" 发送到 roomMap。

What you did is appending both [1] and "\n" into the list "roomMap".您所做的是将 [1] 和“\n”都附加到列表“roomMap”中。 So, for every single iteration, you are pushing 2 elements ([1] and "\n") to the list.因此,对于每一次迭代,您都将 2 个元素([1] 和 "\n")推送到列表中。 A list is not a string, so you do not need to append the whitespace character.列表不是字符串,因此您不需要 append 空格字符。

Try using:尝试使用:

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

Here you go:这里是 go:

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

print() already go to next line. print() 已经 go 到下一行。 This print:这个打印:

50
1
1
1
1 #etc..

If you want a list of lists, just add brackets如果你想要一个列表列表,只需添加括号

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

This print这个印刷品

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

try this尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM