Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace a numerical value in a Python list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Please don’t roast me thanks so much

>Solution :

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']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading