[Python] How can I use list comprehensions to process a nested list?

Discussão em 'Python' iniciado por Stack, Junho 6, 2025.

  1. Stack

    Stack Membro Participativo

    I have this nested list:

    l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]


    I want to convert each element in l to float. I have this code:

    newList = []
    for x in l:
    for y in x:
    newList.append(float(y))


    How can I solve the problem with a nested list comprehension instead?


    See also: How can I get a flat result from a list comprehension instead of a nested list?

    Continue reading...

Compartilhe esta Página