List comprehension on a nested list?

后端 未结 12 943
情话喂你
情话喂你 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:20

    Here is how to convert nested for loop to nested list comprehension:

    Here is how nested list comprehension works:

                l a b c d e f
                ↓ ↓ ↓ ↓ ↓ ↓ ↓
    In [1]: l = [ [ [ [ [ [ 1 ] ] ] ] ] ]
    In [2]: for a in l:
       ...:     for b in a:
       ...:         for c in b:
       ...:             for d in c:
       ...:                 for e in d:
       ...:                     for f in e:
       ...:                         print(float(f))
       ...:                         
    1.0
    
    In [3]: [float(f)
             for a in l
       ...:     for b in a
       ...:         for c in b
       ...:             for d in c
       ...:                 for e in d
       ...:                     for f in e]
    Out[3]: [1.0]
    

    For your case, it will be something like this.

    In [4]: new_list = [float(y) for x in l for y in x]
    

提交回复
热议问题