为什么数组中的输入会覆盖每一行的值 [英] why does the input in the array overwrites the values of each row

查看:60
本文介绍了为什么数组中的输入会覆盖每一行的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码

x=3
a=x*[x*[0]]
for i in range(0,x):
   for j in range(0,x):
       dt=int(input("insert data: "))
       a[i][j]=dt
       print(a)

它应该只在要求时添加数字,但是由于某种原因,它会填充所有行中的数字

and it's supposed to just add the numbers when is asked, but for some reason it fills the numbers in all the rows

推荐答案

您刚刚创建了3个行,且具有与a=x*[x*[0]]相同的引用. x*[0]仅构建一次,并通过外部乘法运算符在所有行上传播.

you just created 3 rows with the same reference with a=x*[x*[0]]. x*[0] is built once, and propagated on all rows by the outer multiply operator.

更改行会更改所有行.请注意,它可能很有用(但显然没有用)

Changing a row changes all the rows. Note that it can be useful (but not there obviously)

相反(使用列表理解):

Do that instead (using a list comprehension):

a=[x*[0] for _ in range(x)]

所以每一行的引用都是分开的

so references of each row are separated

这篇关于为什么数组中的输入会覆盖每一行的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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