如何在python中声明零数组(或特定大小的数组)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4056768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare array of zeros in python (or an array of a certain size)
提问by user491880
I am trying to build a histogram of counts... so I create buckets. I know I could just go through and append a bunch of zeros i.e something along these lines:
我正在尝试构建计数的直方图......所以我创建了桶。我知道我可以通过并附加一堆零,即沿着这些线的东西:
buckets = []
for i in xrange(0,100):
buckets.append(0)
Is there a more elegant way to do it? I feel like there should be a way to just declare an array of a certain size.
有没有更优雅的方法来做到这一点?我觉得应该有一种方法可以声明一个特定大小的数组。
I know numpy has numpy.zerosbut I want the more general solution
我知道 numpy 有,numpy.zeros但我想要更通用的解决方案
采纳答案by dan04
buckets = [0] * 100
Careful - this technique doesn't generalize to multidimensional arrays or lists of lists. Which leads to the List of lists changes reflected across sublists unexpectedlyproblem
小心 -此技术不能推广到多维数组或列表列表。这导致列表更改意外地反映在子列表中的问题
回答by mjhm
You can multiply a listby an integer nto repeat the listntimes:
您可以将 a 乘以一个list整数n来重复listn次数:
buckets = [0] * 100
回答by AndiDog
The simplest solution would be
最简单的解决方案是
"\x00" * size # for a buffer of binary zeros
[0] * size # for a list of integer zeros
In general you should use more pythonic code like list comprehension (in your example: [0 for unused in xrange(100)]) or using string.joinfor buffers.
一般来说,您应该使用更多的 Pythonic 代码,如列表理解(在您的示例中:)[0 for unused in xrange(100)]或string.join用于缓冲区。
回答by fabrizioM
回答by Russell Borogove
Depending on what you're actually going to do with the data after it's collected, collections.defaultdict(int) might be useful.
取决于您在收集数据后实际打算如何处理数据, collections.defaultdict(int) 可能会很有用。
回答by meeDamian
Use this:
用这个:
bucket = [None] * 100
for i in range(100):
bucket[i] = [None] * 100
OR
或者
w, h = 100, 100
bucket = [[None] * w for i in range(h)]
Both of them will output proper empty multidimensional bucket list 100x100
他们都将输出适当的空多维桶列表 100x100
回答by OK.
Just for completeness: To declare a multidimensional list of zeros in python you have to use a list comprehension like this:
只是为了完整性:要在 python 中声明一个多维零列表,您必须使用这样的列表理解:
buckets = [[0 for col in range(5)] for row in range(10)]
to avoid reference sharing between the rows.
以避免行之间的引用共享。
This looks more clumsy than chester1000's code, but is essential if the values are supposed to be changed later. See the Python FAQfor more details.
这看起来比chester1000 的代码更笨拙,但如果值应该在以后更改,则是必不可少的。有关更多详细信息,请参阅Python 常见问题解答。
回答by Archit
Well I would like to help you by posting a sample program and its output
好吧,我想通过发布示例程序及其输出来帮助您
Program :-
程序 :-
t=input("")
x=[None]*t
y=[[None]*t]*t
for i in range(1,t+1):
x[i-1]=i;
for j in range(1,t+1):
y[i-1][j-1]=j;
print x
print y
Output :-
输出 :-
2
[1, 2]
[[1, 2], [1, 2]]
I hope this clears some very basic concept of yours regarding their declaration. To initialize them with some other specific values,like initializing them with 0..you can declare them as :
我希望这可以清除您关于他们的声明的一些非常基本的概念。要使用其他一些特定值初始化它们,例如使用 0.. 初始化它们,您可以将它们声明为:
x=[0]*10
x=[0]*10
Hope it helps..!! ;)
希望能帮助到你..!!;)
回答by renatov
If you need more columns:
如果您需要更多列:
buckets = [[0., 0., 0., 0., 0.] for x in range(0)]
回答by IAbstract
The question says "How to declare array of zeros ..." but then the sample code references the Python list:
问题是“如何声明零数组......”但是示例代码引用了 Python 列表:
buckets = [] # this is a list
However, if someone is actually wanting to initialize an array, I suggest:
但是,如果有人真的想要初始化一个数组,我建议:
from array import array
my_arr = array('I', [0] * count)
The Python purist might claim this is not pythonicand suggest:
Python 纯粹主义者可能会声称这不是Pythonic并建议:
my_arr = array('I', (0 for i in range(count)))
The pythonicversion is very slow and when you have a few hundred arrays to be initialized with thousands of values, the difference is quite noticeable.
在Python的版本是非常缓慢的,当你有几百个阵列成千上万值进行初始化,差距十分明显。

