1

Newbie question: I have 2 lists:

# The first one is a list of lists:
list_a = [[1,5,3],[4,2],[2,3,3,5],[2,3,1]]
# The second one is a list of strings:
list_b = ['a','b','c','d','e']

The question is: How can I create a new list list_c, that looks like this?

list_c = [['a','e','c'], ['d','b'], ['b','c','c','e'],['b','c','a']]

So basically, what I need to do is some sort of mapping out the values of list_a which represents the indices of list_b.

I tried doing nested for loops, but I'm really confused.

1
  • Python indexes lists (etc) starting from 0, so it would be better if you worked in zero-based indices if possible, rather than having to subtract 1 every time. e.g. list_a = [[0,4,2],... I am not suggesting that you edit the question now, as this would break answers that have already been posted, but something to consider in future. Commented Jul 5, 2020 at 22:16

5 Answers 5

2

You can try this:-

list_c = [[list_b[i-1] for i in j] for j in list_a]
print(list_c)

Output:-

[['a', 'e', 'c'], ['d', 'b'], ['b', 'c', 'c', 'e'], ['b', 'c', 'a']]
Sign up to request clarification or add additional context in comments.

Comments

0

If you're not concerned about index errors, you can express this concisely using a nested list comprehension:

list_c = [[list_b[i-1] for i in sublist] for sublist in list_a]

Comments

0

Here you go:

list_c = [
    [list_b[item - 1] for item in inner_list] for inner_list in list_a
]
print(list_c)

Output:

[['a', 'e', 'c'], ['d', 'b'], ['b', 'c', 'c', 'e'], ['b', 'c', 'a']]

Comments

0

You need to do something like that:

for index, item in enumerate(list_a):
 for list_index, list_item in enumerate(list_a[index]):
    list_a[index][list_index] = None
    list_a[index][list_index] = list_b[list_item]

print(list_a)

Output:

[['b', 'f', 'd'], ['e', 'c'], ['c', 'd', 'd', 'f'], ['c', 'd', 'b']]

Comments

0

There's a module for that: operator. You can use operator.itemgetter():

from operator import itemgetter as ig

list_a = [[1,5,3],[4,2],[2,3,3,5],[2,3,1]]
list_b = ['a','b','c','d','e']
list_c = [ig(*[i-1 for i in l])(list_b) for l in list_a]

print(list_c)

Output:

[('a', 'e', 'c'), ('d', 'b'), ('b', 'c', 'c', 'e'), ('b', 'c', 'a')]

It results in a list of tuples, which can be adjusted by adding list() to ig(*[i-1 for i in l])(list_b).

This would of course be more neat if the indices in list_a were not shifted by one unit:

from operator import itemgetter as ig

list_a = [[0,4,2],[3,1],[1,2,2,4],[1,2,0]]
list_b = ['a','b','c','d','e']
list_c = [ig(*l)(list_b) for l in list_a]

print(list_c)

Output:

[('a', 'e', 'c'), ('d', 'b'), ('b', 'c', 'c', 'e'), ('b', 'c', 'a')]

Comments

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.