How to replace a numerical value in a Python list

Question:

So I got this list of lists:

lst = [[0,1],2,[3]]

and I got a list of tuples:

lst_2 = [("x1","y1"),("x2","y2"), ("x3","y3"), ("x4","y4")]

I want to replace values inside lst with the index 0 value of each of the tuples in lst_2, and the tuple taken depends on the numerical value in lst. So it becomes:

lst = [["x1","x2"], "x3", ["x4"]]

Please don’t roast me thanks so much

Asked By: rose

||

Answers:

Try this:

lst = [[0,1],2,[3]]
lst_2 = [("x1","y1"),("x2","y2"), ("x3","y3"), ("x4","y4")]

res = []
for l in lst:
    if isinstance(l, list):
        res += [[lst_2[i][0] for i in l]]
    else:
        res += [lst_2[l][0]]
print(res)

Or with List Comprehensions:

res = [[lst_2[i][0] for i in l] if isinstance(l, list) else lst_2[l][0] for l in lst]

[['x1', 'x2'], 'x3', ['x4']]
Answered By: I'mahdi

You could use recursion to allow lst to have deeper levels of nesting:

def produce(template, data):
    return [
        produce(nested, data) for nested in template
    ] if isinstance(template, list) else data[template][0]

# Example
lst = [[0,[1]],2,[3]]
lst_2 = [("x1","y1"),("x2","y2"), ("x3","y3"), ("x4","y4")]
result = produce(lst, lst_2)
Answered By: trincot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.