List comprehension on a nested list?

后端 未结 12 944
情话喂你
情话喂你 2020-11-22 07:57

I have this nested list:

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


        
12条回答
  •  太阳男子
    2020-11-22 08:26

    Since i am little late here but i wanted to share how actually list comprehension works especially nested list comprehension :

    New_list= [[float(y) for x in l]
    

    is actually same as :

    New_list=[]
    for x in l:
        New_list.append(x)
    

    And now nested list comprehension :

    [[float(y) for y in x] for x in l]
    

    is same as ;

    new_list=[]
    for x in l:
        sub_list=[]
        for y in x:
            sub_list.append(float(y))
    
        new_list.append(sub_list)
    
    print(new_list)
    

    output:

    [[40.0, 20.0, 10.0, 30.0], [20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0], [30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0], [100.0, 100.0], [100.0, 100.0, 100.0, 100.0, 100.0], [100.0, 100.0, 100.0, 100.0]]
    

提交回复
热议问题