列表列表中的Python 3列表解析以转换类型 [英] Python 3 list comprehension in list of lists to convert types

查看:82
本文介绍了列表列表中的Python 3列表解析以转换类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下列表列表:

list1 = [['1.1', '1.2', '1.3'], ['2.1', '2.2', '2.3'], ...]

要理解将其转换为浮点数的字符串列表,可以使用

To comprehend a list of strings to convert them to floats one could use

list1[0] = [float(i) for i in list1[0]]

但是我试图理解一个浮动列表的列表并没有成功:

But my attempt to comprehend a list of lists of floats didn't quite work:

list1 = [[float(j) for j in list1[i]] for i in list1]

由于

TypeError:列表索引必须是整数或切片,而不是列表

TypeError: list indices must be integers or slices, not list

是否有一种无需明确使用循环即可进行此类列表理解的方法?

Is there a way to do this sort of list comprehension without using loops explicitly?

推荐答案

[[float(j) for j in i] for i in list1]

应该这样做

这篇关于列表列表中的Python 3列表解析以转换类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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