将嵌套列表中的特定组件从字符串更改为浮点

时间:2018-09-29 23:22:56

标签: python list

我有一个嵌套的字符串列表。我想将嵌套列表的第一部分更改为整数,第二部分更改为浮点数。

>>> mylist = [['1','2','3'],['5','6','7']]
>>> datl3 = [[int(x) for x in line[0]] + line[1:] for line in mylist]
>>> type(datl3[0][0])
<type 'int'>
>>> 
>>> # turn second element to float
... datl4 = [line[0] + [float(x) for x in line[1]] + line[2] for line in datl3]
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

如何将第二个组件更改为浮动?

2 个答案:

答案 0 :(得分:3)

您可以使用精美的包装来做到这一点:

>>> mylist = [['1','2','3'],['5','6','7']]
>>> [[int(first),float(second),*rest] for first, second, *rest in mylist]
[[1, 2.0, '3'], [5, 6.0, '7']]

答案 1 :(得分:0)

使用列表理解

l = [[int(i[0]), float(i[1]), i[2]] for i in l]
[[1, 2.0, '3'], [5, 6.0, '7']]