简体   繁体   中英

Python: use dict and list of tuples to create a numpy array

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:

  • at position (0, 1) of the numpy array, I want a numpy array with values (3, 2) ;
  • at position (0, 4) of the numpy array, I want a numpy array with values (3, 3) ;
  • at position (2, 3) of the numpy array, I want a numpy array with values (2, 2) ;
  • at all other positions of the numpy array, I want a numpy array with values (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.

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