嵌套列表上的列表理解? [英] List comprehension on a nested list?

查看:63
本文介绍了嵌套列表上的列表理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个嵌套列表:

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.我的解决方法是这样:

Now, what I want to do is convert each element in a list to float. My solution is this:

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

但这可以使用嵌套列表理解来完成吗?

But can this be done using nested list comprehension, right?

我要做的是:

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

但是结果是一堆100的总数为2400.

But then the result is bunch of 100's with the sum of 2400.

任何解决方案,将不胜感激.谢谢!

any solution, an explanation would be much appreciated. Thanks!

推荐答案

下面是使用嵌套列表推导的方法:

Here is how you would do this with a nested list comprehension:

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

这将为您提供一个列表列表,与您开始时的列表类似,只是使用浮点数而不是字符串.如果您想要一个平面列表,则可以使用[float(y) for x in l for y in x].

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

这篇关于嵌套列表上的列表理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆