I am wondering if I can replace values of a list with elements of another list based on the index in Python:
let's say
a=[3, 2, 8, 7, 0]
d=['a','b','c','d','e','f','g','h','i']
I want to replace the elements of list a with the elements of list d. Values of list a define the index number of list d.
I want a list like c,
c=['d','c','i','a']
CodePudding user response:
a = [3,2,8,7,0]
b = ['a','b','c','d','e','f','g','h','i']
l = [b[i] for i in a]
# d, c, i, a
CodePudding user response:
a=[3, 2, 8, 7, 0]
d=['a','b','c','d','e','f','g','h','i']
d = np.array(d)
d[[a]]
This can be done with the help of numpy.
CodePudding user response:
I would do it in this manner: (anyway I am curious if there is another, simplest way)
c=[]
a=[3, 2, 8, 7, 0]
d=['a','b','c','d','e','f','g','h','i']
for index in a:
c.append(d[index])
print(c)
result: c = ['d', 'c', 'i', 'h', 'a']