List comprehension on a nested list?

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

    If you don't like nested list comprehensions, you can make use of the map function as well,

    >>> from pprint import pprint
    
    >>> l = 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']] 
    
    >>> pprint(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']]
    
    >>> float_l = [map(float, nested_list) for nested_list in l]
    
    >>> pprint(float_l)
    [[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]]
    
    0 讨论(0)
  • 2020-11-22 08:29
    >>> 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']]
    >>> new_list = [float(x) for xs in l for x in xs]
    >>> new_list
    [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]
    
    0 讨论(0)
  • 2020-11-22 08:29
        deck = [] 
        for rank in ranks:
            for suit in suits:
                deck.append(('%s%s')%(rank, suit))
    

    This can be achieved using list comprehension:

    [deck.append((rank,suit)) for suit in suits for rank in ranks ]
    
    0 讨论(0)
  • 2020-11-22 08:34

    Yes, you can do it with such a code:

    l = [[float(y) for y in x] for x in l]
    
    0 讨论(0)
  • 2020-11-22 08:40

    Not sure what your desired output is, but if you're using list comprehension, the order follows the order of nested loops, which you have backwards. So I got the what I think you want with:

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

    The principle is: use the same order you'd use in writing it out as nested for loops.

    0 讨论(0)
  • 2020-11-22 08:44

    Yes you can do the following.

    [[float(y) for y in x] for x in l]
    
    0 讨论(0)
提交回复
热议问题