简体   繁体   English

如何创建一个包含元素 0 n 次的列表? python

[英]How to create a list with the element 0 n times? python

Is this the right way to go about it?这是go的正确方法吗? Or does 0 also have to be in [] brackets?还是 0 也必须在 [] 括号中?

list = [0 * i for i in range(n)]

If yes then how is it different from writing it like this right away?如果是,那么它与立即这样写有什么不同?

list = [0]* n

Use [0] * n , where n is your desired no.使用[0] * n ,其中n是您想要的编号。 of elements in the list.列表中的元素。

In the first instance you are creating a list comprehension in which values within the range 0 to (n-1) are being inserted as elements into a list however they are also individually being multiplied by zero, leaving them as zero.在第一个实例中,您正在创建一个列表推导式,其中 0 到 (n-1) 范围内的值作为元素插入到列表中,但是它们也单独乘以零,使它们为零。

Whilst in the second instance which you had written as list = [0 * n] you are inserting a single value into a list: 0 multiplied by n - thus leaving the list length at 1.在您编写为list = [0 * n]的第二个实例中,您将单个值插入到列表中:0 乘以 n - 因此列表长度为 1。

(now you have adjusted it to match our answers) (现在你已经调整它以匹配我们的答案)

ls = [0] * n

And now you have phrased your question as: Why is your list comprehension technique different to the, recently amended approach, of multiplying the list by n.现在您已经将您的问题表述为:为什么您的列表理解技术与最近修改的将列表乘以 n 的方法不同。 This is because as previously mentioned in the list comprehension approach you are multiplying each element by zero before inserting it into the list, whilst the 2nd approach you are multiplying the entire list by n causing it to become length n, filled with zeros.这是因为如前面在列表理解方法中提到的,您在将每个元素插入列表之前将其乘以零,而第二种方法是将整个列表乘以 n,使其变为长度 n,并用零填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM