我有一个嵌套的字符串列表。我想将嵌套列表的第一个组件更改为整数,第二个组件更改为 float 。
>>> 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'
如何将第二个组件更改为 float ?
最佳答案
您可以使用花式解包来执行此操作:
>>> 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']]
关于python - 将嵌套列表中的特定组件从字符串更改为浮点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52573333/