Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python数组列插入_Python_Arrays - Fatal编程技术网

Python数组列插入

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

我在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
['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]]
>>>