Home > database >  Replace nested list index values with actual values
Replace nested list index values with actual values

Time:01-03

I have 2 lists and 1 is a nested list

list1 = [[0,1],[0,2],[1,2]]
list2 = ['a','b','c']

I want to replace the nested list index values with the actual values such that the output looks like below

Expected Output

[['a','b'],['a','c'],['b','c']]

CodePudding user response:

One approach:

res = [[list2[ei] for ei in e] for e in list1]
print(res)

Output

[['a', 'b'], ['a', 'c'], ['b', 'c']]

CodePudding user response:

An other approach

d = [[0,1],[0,2],[1,2]]
l = ['a','b','c']
r = [[l[i],l[j]] for i,j in d]
print(r)
#[['a', 'b'], ['a', 'c'], ['b', 'c']]

CodePudding user response:

Alternatively, you could use operator lib - itemgetter to achieve the desired outcome. Prob. it's not as elegant as prev. post, but just to show another way to get multiple items at once: (it could be faster if the lists is quite large)

from operator import itemgetter

nums = [[0, 1], [0, 2], [1, 2]]
char = ['a', 'b', 'c']

ans = [ itemgetter(*lst)(chars) for lst in nums]

print(ans)
# [('a', 'b'), ('a', 'c'), ('b', 'c')]
  • Related