I have five key/value pairs in a python dict object:
dict1 = {0:3, 1:2, 2:2, 3:2, 4:3}
And I have a list of tuples:
list_of_tuples = [(0, 1), (0, 4), (2, 3)]
I want a numpy array of shape (5, 5, 2)
that contains the value from the dict object for each tuple value. I get 5
from the number of keys in the dict object, and 2
from the number of values in each tuple.
That is:
(0, 1)
of the numpy array, I want a numpy array with values (3, 2)
; (0, 4)
of the numpy array, I want a numpy array with values (3, 3)
; (2, 3)
of the numpy array, I want a numpy array with values (2, 2)
; (4, 4)
, where I use (4, 4)
as an indicator of an empty spot.
Is there a nice, Pythonic way of doing this?
You can create an array of 4s using np.full
and then populate it:
a = np.full((5, 5, 2), 4)
for x, y in list_of_tuples:
a[x, y] = dict1[x], dict1[y]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.