使列表独立于自身(?) [英] Making a list independent of itself(?)

查看:58
本文介绍了使列表独立于自身(?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用列表,并试图显示以下代码段:

I am experimenting with lists and was trying to get the following code segment to display:

----------
---hello--
----------

但是要做到这一点,我需要使3个"listSmall"彼此独立.有办法吗?

But to do this I need to get the 3 'listSmall's to be independent of one another. Is there a way to do this?

(

当然是当前输出:

---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指向同一可变列表3次,因此当您通过这些引用中的一个更改此可变列表时,您将在所有这三个引用中看到此更改.

makes listBig point three times to the same mutable list, so when you change this mutable list through on of these references, you will see this change through all the three.

您应该列出三个不同的列表:

You should make three distinct lists:

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))

这篇关于使列表独立于自身(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆