Reputation: 35
I have been reading this page Convert Python list of strings into floats, where list also contains words
And tried to implement this but I can't for a double list.
I have a double list that looks like this
Positions = [['ace','first', '10','-29'],['best','second','200','-10']]
This is what I get from opening a file. What I would like to do is remove the strings from the 2nd and 3rd index spots in the list so as to get both these positions as integers and not strings. Is there a way that I can open the file to mp remove these strings
or
is there a way that I can remove the strings by applying a method to my double list??
Upvotes: 1
Views: 123
Reputation: 60014
What you have is nested loops. It's pretty much the same:
>>> L = [['ace','first', '10','-29'],['best','second','200','-10']]
>>> for i in L:
... i[3] = int(float(i[3]))
... i[2] = int(float(i[2]))
...
...
>>> print L
[['ace', 'first', 10, -29], ['best', 'second', 200, -10]]
Upvotes: 0
Reputation: 114035
Get a list of lists, where each sublist has the int represented in the last two positions of each sublist in Positions
:
[[int(i) for i in L[-2:]] for L in Positions]
Turn the string representations of the integers in Positions
into int
s:
[[int(i) for i in L if ((i.startswith('-') and all(char.isdigit() for char in i)) or all(char.isdigit() for char in i) else i] for L in Positions]
Upvotes: 2