使用np.zero

时间:2015-09-14 09:39:38

标签: python arrays python-2.7 numpy

我可能只是太傻了,但我需要一个快速版本:

for i in range(0,4):
    c.append((0,0,0))

out: [(0,0,0),(0,0,0),(0,0,0),(0,0,0)] 

我想在 zero filled tuple 中创建一个shape of (xL,),其中x是(0,0,0)'s的数量...我现在有三个工作解决方案,没有其中包括np.zero

2 个答案:

答案 0 :(得分:3)

您可以使用numpy.zeros

>>> import numpy as np
>>> np.zeros(4*3).reshape(4,3)
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

如果你想把它作为元组:

>>> map(tuple,np.zeros(4*3).reshape(4,3))
[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0)]

或者@Divakar在评论中提到更优雅的方式在zeros函数中使用服装形状:

map(tuple,np.zeros((4,3),dtype=int))

答案 1 :(得分:3)

You could go the structured array route:

In [304]: np.zeros((10,),dtype='i,i,i')
Out[304]: 
array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
       (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], 
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')])

Strictly speaking these are not tuples - it just displays them as tuples.

But to get a list of tuples, just use tolist:

In [305]: np.zeros((10,),dtype='i,i,i').tolist()
Out[305]: 
[(0, 0, 0),
 (0, 0, 0),
 (0, 0, 0),
 ...
 (0, 0, 0),
 (0, 0, 0),
 (0, 0, 0)]

You can generalize the tuple length with a string generated with ','.join(['i']*3)

For a non-structured approach I would use

[tuple(x) for x in np.zeros((10,3),int)]

In Python3 (especially) I prefer a list comprehension over the equivalent map: list(map(tuple, np.zeros((10,3),int))).

Some timings (L=10**5):

structured array:

In [340]: timeit np.zeros((L,),dtype='i,i,i')
10000 loops, best of 3: 77.5 µs per loop

structured array converted to list of tuples:

In [341]: timeit np.zeros((L,),dtype='i,i,i').tolist()
10 loops, best of 3: 73.6 ms per loop

list of tuples from 2d array:

In [342]: timeit [tuple(x) for x in np.zeros((L,3),int)]
1 loops, best of 3: 223 ms per loop

pure python list of tuples:

In [343]: timeit [(0,0,0) for _ in range(L)]
100 loops, best of 3: 15.1 ms per loop

best list of tuples (@swensel):

In [344]: timeit [(0,0,0)]*L
1000 loops, best of 3: 429 µs per loop

If the ultimate goal is a list of tuples, stick with Python.

If the goal is a numpy structured array, go direct.


One thing to be wary about when using [(0,0,0)]*L; this achieves its speed by simply replicating the pointers. Each entry in the list points to the same tuple. With nested lists that can have serious problems:

x = [[0,0,0]]*L
x[1][1] = 3

changes every sublist. With tuples this isn't so much an issue because they are immutable.