我正在尝试使用列表,并试图显示以下代码段:
----------
---hello--
----------
但要做到这一点,我需要让3’listssmall相互独立。有办法吗?
(
当然,电流输出是:
---hello--
---hello--
---hello--
)
listSmall = ['-','-','-','-','-','-','-','-','-','-',]
listBig = [listSmall, listSmall, listSmall]
word = 'hello'
wordPosX = 3
wordPosY = 2
for i in word:
listBig[wordPosY][wordPosX] = i
wordPosX = wordPosX + 1
i = 0
while i != 3:
print ''.join(listBig[i])
i = i + 1
最佳答案
这是因为list
是可变的。
listBig = [listSmall, listSmall, listSmall]
使
listBig
指向同一可变列表三次,因此当您通过这些引用中的一个更改此可变列表时,您将看到这三个更改。您应该列出三个不同的列表:
listBig = [ ['-'] * 10 for _ in range(3)]
完全不需要
listSmall
。整个代码:
listBig = [ ['-'] * 10 for _ in range(3)]
word = 'hello'
wordPosX, wordPosY = 3, 1
listBig[wordPosY][3: (3+len(word))] = word
for v in listBig:
print(''.join(v))