二维列表推导 Python 2

克里斯蒂安·皮克勒

我想知道如何将列表中的字符串转换为整数。

例如:

输入:

data = [
['1', '-160'],
['2', '-3000'],
['4', '-2'],
['5', '0.27'], ]

data = [int(a) for a in data[0]] #This converts only the first row of the list - I need the whole list converted 


print(data)

输出:

[[1, -160], [2, -3000],[4, -2],[5, 0.27]]

这样做的原因是因为我想对列表进行排序,但是当数字带有撇号时这不起作用。

我希望任何人都可以帮助我:)

亚历克斯

这将是正确的列表理解:

[[float(c) for c in row] for row in data]

请注意,我已更改int(...)float(...)处理您输入中的浮点数。这给出了输出:

[[1.0, -160.0], [2.0, -3000.0], [4.0, -2.0], [5.0, 0.27]]

根据您的评论,如果您的列表中有字母,您还if可以在列表理解中添加一个语句:

[[float(c) if c.lstrip('-').isdigit() else c for c in row] for row in data ]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章