2

I have a nested list of strings. I want to change the first component of the nested list to integer, second to 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'

How I can I change the second component to float?

2 Answers 2

2

You can use fancy unpacking to do this:

>>> 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']]
Sign up to request clarification or add additional context in comments.

Comments

0

Using list comprehension

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.