我有这样一个嵌套列表:

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']]

我想把l中的每个元素都转换为float。我有这样的代码:

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

如何用嵌套的列表理解来解决这个问题?


另请参阅:如何从列表理解而不是嵌套列表中获得平坦的结果?


当前回答

    deck = [] 
    for rank in ranks:
        for suit in suits:
            deck.append(('%s%s')%(rank, suit))

这可以通过列表理解来实现:

[deck.append((rank,suit)) for suit in suits for rank in ranks ]

其他回答

>>> 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]

如果需要一个扁平的列表:

[y for x in l for y in x]

如果需要一个嵌套列表(list In list):

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

下面是如何将嵌套for循环转换为嵌套列表推导式:

下面是嵌套列表理解的工作原理:

            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]

对于你的例子,如果你想要一个平面列表,它会是这样的。

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

不确定您想要的输出是什么,但如果您使用的是列表推导式,则顺序遵循嵌套循环的顺序,这是向后的。我拿到了你想要的东西

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

其原则是:使用与编写嵌套for循环相同的顺序。

是的,你可以这样做。

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