0

I have list with names and their correspondent number. Is there any easy way to replace the correspondent number in a n array back with the correct name? here is an example thanks!

list =[{'Nikolas', 'Kate', 'George'}, [0, 1, 2 ]]

np_array_1 = np.array([1, 2])
np_array_2= np.array([0])
etc.

I mean in a for loop or something, as I have plenty of arrays.

So I would like to get:

np_array_1 = ['Kate', 'George']
np_array_2= ['Nikolas']
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

1

Instead of set(set will not maintain order) make a nested list like:

lst =[['Nikolas', 'Kate', 'George'], [0, 1, 2 ]]

make a dictionary to store name and numbers:

d=dict(zip(lst[1],lst[0]))  # here 0 index in lst will have all the numbers and 1 index in lst will have all the names

print(d)
#{0: 'Nikolas', 1: 'Kate', 2: 'George'}

Now, if you want o replace numbers with names you can do:

suppose there is a list with numbers and y want to replace them with names

l=[1,0,2]
e=[]
for x in l: 
    e.append(d[x])

print(e)
#['Kate', 'Nikolas', 'George']
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • Now it is also easy (and readable) to transform to a simple list-comp: `e = [d[x] for x in l]` – Tomerikoo Jan 16 '23 at 10:09
  • Lastly, I guess you answered for the general case, but here it is obviously redundant to have a list which is the natural indexes... It can also just be `e = [lst[0][i] for i in l]` - no need for a dict (just like [this answer](https://stackoverflow.com/a/6632209/6045800)...) – Tomerikoo Jan 16 '23 at 10:11