Matt Inwood
Matt Inwood

Reputation: 137

Replacing a list of indices with a string in python

I have a set of indices in a list:

[2 0 3 4 5]

And I want to replace them by values stored in another list:

[a b c d e f g]

And output:

[c a d e f]

I tried this code:

for line in indices:
    print(line)
    for value in line:
        value = classes[value]
    print(line)
    break

which prints the original list twice. Is there a way to replace the elements or am I forced to create a new list of lists?

Upvotes: 0

Views: 57

Answers (3)

Akshay Hazari
Akshay Hazari

Reputation: 3267

idxs  = [2, 0, 3, 4, 5]
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
map(lambda x : chars[x],idxs)
=> ['c', 'a', 'd', 'e', 'f']

Or

reduce(lambda x,y: x+[chars[y]],idxs,[])
=> ['c', 'a', 'd', 'e', 'f']

Upvotes: 1

Iman Mirzadeh
Iman Mirzadeh

Reputation: 13550

you can also use chr() function which converts int to characters(ascii table)

>>> a = [2 0 3 4 5]
>>> [chr(i+97) for i in a]
['c', 'a', 'd', 'e', 'f']

Upvotes: 0

Óscar López
Óscar López

Reputation: 235994

This looks like a good place to use a list comprehension, try this - the idiomatic solution:

idxs  = [2, 0, 3, 4, 5]
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

[chars[i] for i in idxs]
=> ['c', 'a', 'd', 'e', 'f']

Of course, we could do the same using explicit looping as you intended, but it's not as cool as the previous solution:

ans = []
for i in idxs:
    value = chars[i]
    ans.append(value)

ans
=> ['c', 'a', 'd', 'e', 'f']

And as a final alternative - I don't know why you want to "replace the elements" in the input list (as stated in the question), but sure, that's also possible, but not recommended - it's simpler and cleaner to just create a new list with the answer (as shown in the two previous snippets), instead of changing the original input:

for pos, val in enumerate(idxs):
    idxs[pos] = chars[val]

idxs
=> ['c', 'a', 'd', 'e', 'f']

Upvotes: 3

Related Questions