Python数组列插入
我在python中使用数组,我想在2d数组中插入一个数组作为列 我发现,出于某种原因,我的专栏只写了单词的最后一个元素[]Python数组列插入,python,arrays,Python,Arrays,我在python中使用数组,我想在2d数组中插入一个数组作为列 我发现,出于某种原因,我的专栏只写了单词的最后一个元素[] words = ['first','second','third','fourth','fifth'] tab = [[None]*5]*len(words) for i in range(len(words)): tab[i][0] = words[i] for i in range(len(words)): print(tab[i]) #output
words = ['first','second','third','fourth','fifth']
tab = [[None]*5]*len(words)
for i in range(len(words)):
tab[i][0] = words[i]
for i in range(len(words)):
print(tab[i])
#output
['fifth', None, None, None, None]
['fifth', None, None, None, None]
['fifth', None, None, None, None]
['fifth', None, None, None, None]
['fifth', None, None, None, None]
您正在使用复制值
[None]*5
及
你的需要:
words = ['first','second','third','fourth','fifth']
tab = [[[None] for i in range(5)] for i in range(len(words))]
for i in range(len(words)):
tab[i][0] = words[i]
for i in range(len(words)):
print(tab[I])
出局
你的预期输出是什么?谢谢,但我不明白我们是怎么得到这个的:它有点像字符串池?[[None]因为我在范围(5)]中意味着五步[None]:[[None],[None],[None],[None],[None],[None],[None],[None],[None],[None]]当你使用“[[None]*5]*len(words)”,主要问题是:“*len(words)”你只复制它,而改变之痒就是你的改变所有这一切所以参考文献也是“克隆的”是的你是对的!它的克隆)
words = ['first','second','third','fourth','fifth']
tab = [[[None] for i in range(5)] for i in range(len(words))]
for i in range(len(words)):
tab[i][0] = words[i]
for i in range(len(words)):
print(tab[I])
['first', [None], [None], [None], [None]]
['second', [None], [None], [None], [None]]
['third', [None], [None], [None], [None]]
['fourth', [None], [None], [None], [None]]
['fifth', [None], [None], [None], [None]]
>>>