Reputation: 27
I have a long, un-grouped list and I am trying to convert the decimal numbers from strings to floats. However, they exist in a list that has other strings and integers. Here is an example of what I am working with:
List1 = ['01/01/2020', 'AType', '4.30', '789.33', '02/01/2020', 'BType', '342.77', '84', '03/01/2020', 'CType', '2', '245.22', etc, etc, etc,]
I am aware of the way to convert strings into integers [int(f) if f.isdigit() else f for f in listone]
but that does not seem to work with [float(x.strip(' "')) if x.isdecimal() else x for x in listone]
. How do I convert the decimal strings into floats?
Upvotes: 0
Views: 177
Reputation: 71562
You might write a function that will convert the strings according to whatever rules you want, and then map it over the list:
from typing import Union
def convert_string(x: str) -> Union[str, int, float]:
"""Attempts to convert a string to an int or float.
Returns the string unchanged if no conversion possible."""
try:
return int(x)
except ValueError:
pass
try:
return float(x)
except ValueError:
return x
>>> list(map(convert_string, ["foo", "1.21", "1"]))
['foo', 1.21, 1]
Practically speaking, I think it'd be better to group these values, perhaps into a NamedTuple
?
>>> from typing import List, NamedTuple
>>> class Thingy(NamedTuple):
... date: str
... type: str
... num1: float
... num2: float
...
>>> def build_thingy(elements: List[str]) -> Thingy:
... """Build a Thingy from input list of 4 elements.
... Raises if the input list is not valid."""
... [date, type, num1, num2] = elements
... return Thingy(date, type, float(num1), float(num2))
...
>>> [build_thingy(List1[i:i+4]) for i in range(0, len(List1), 4)]
[Thingy(date='01/01/2020', type='AType', num1=4.3, num2=789.33),
Thingy(date='02/01/2020', type='BType', num1=342.77, num2=84.0),
Thingy(date='03/01/2020', type='CType', num1=2.0, num2=245.22)]
Upvotes: 1