在嵌套列表上列出理解?我有这个嵌套列表: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。我的解决方案是:newList = []for x in l:
for y in x:
newList.append(float(y))但这可以使用嵌套列表理解来完成,对吗?我所做的是:[float(y) for y in x for x in l]但结果是一堆100的总和2400。任何解决方案,将非常感谢解释。谢谢!
3 回答

跃然一笑
TA贡献1826条经验 获得超6个赞
以下是使用嵌套列表理解的方法:
[[float(y) for y in x] for x in l]
这将为您提供一个列表列表,类似于您开始使用的列表,除了浮点数而不是字符串。如果你想要一个平面列表,那么你会使用[float(y) for x in l for y in x]
。

偶然的你
TA贡献1841条经验 获得超3个赞
以下是如何将嵌套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.0In [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]#Which can be written in single line asIn [4]: [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[4]: [1.0]

MM们
TA贡献1886条经验 获得超2个赞
不确定你想要的输出是什么,但是如果你正在使用列表理解,那么顺序遵循嵌套循环的顺序,你已经倒退了。所以我得到了我认为你想要的东西:
[float(y) for x in l for y in x]
原则是:使用您在编写嵌套for循环时使用的相同顺序。
添加回答
举报
0/150
提交
取消