0

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?

2
  • Of course it's printing the list twice, you have two calls to print. What do you mean by "replacing the elements"? you don't want to do that! leave the input lists alone, and simply create a new one with the answer, as shown in my solution. Commented Nov 21, 2015 at 1:31
  • Well, I wanted it to print the original list and then the new list, rather than the original twice. So it sounds like, yes, I have to create a second list. Commented Nov 21, 2015 at 1:37

3 Answers 3

3

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']
Sign up to request clarification or add additional context in comments.

Comments

1
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']

Comments

0

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']

1 Comment

values in a are just indices

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.