python - How to get values from a map and set them into a numpy matrix row? -


i have numpy matrix want fill results of function. function returns map of integer values maped row of matrix.

the values returned function like:

{1:6, 2:3, 3:2, 4:2, 5:1} 

then, wrote following code fill in values matrix:

results = np.empty((10, 5), dtype=int)  in range(10):     result = method()     j in range(5):         results[i, j] = result[j] 

i want know if there more properly/efficient way python?

you can values form dictionary , use np.full create expected matrix :

>>> d={1:6, 2:3, 3:2, 4:2, 5:1} >>> vals=d.values() >>> np.full((10,5),list(vals)) array([[ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.],        [ 6.,  3.,  2.,  2.,  1.]]) 

and if method function returns different results in each iteration, can use list comprehension create matrix:

l = np.array([list(method().values()) _ in range(1, 11)]) 

note: since dictionary keys sorted digits , in case keys have sorted hash value, dict.values method returns sorted value based on keys:

>>> list(map(hash, range (1 , 6))) [1, 2, 3, 4, 5] 

if keys not sorted digits, can make method functions return ordered dictionary using collections.ordereddict.

but note since ordereddict ordered insertion, if want, can use it. if want order based on keys, can use following approach values:

[map(dict.get, range(1, 6)) _ in range(10)] 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -