So i have this code right here to separate only ints or floats out of a file and add them to a list, however when it returns the list, it returns each element on a new line and not the entire list on the same line, and I'm wondering why? the list looks kind of like this: 12 w 21 d23g780nb deed e2 21.87 43 91 - . 222 mftg 21 bx .1 3 g d e 6 de ddd32 3412
def read_numbers(path: str) -> list:
with open(path) as f:
file_elem = f.read().split()
a = []
for x in file_elem:
if x.isnumeric():
a.append(int(x))
elif "." in x:
b = x.replace(".","")
if b.isnumeric():
a.append(float(x))
return a
If I remove the looking for floats part it will only add the ints to the list but it will return the list as intended, Out[101]: [12, 21, 43, 91, 222, 21, 3, 6, 3412, 0, 0, 0, 1, 70, 12, 1, 9, 445, 100] however when adding the floats, it seems that the entire list gets messed up like this
and i'm wondering why?
CodePudding user response:
I created a file like this:
file a:
12 43 12.145 546 23 76 5.54 231.1 32
then I run your code like this:
In [3]: def read_numbers(path: str) -> list:
...: with open(path) as f:
...: file_elem = f.read().split()
...: a = []
...: for x in file_elem:
...: if x.isnumeric():
...: a.append(int(x))
...: elif "." in x:
...: b = x.replace(".","")
...: if b.isnumeric():
...: a.append(float(x))
...: return a
...:
In [4]: read_numbers('./a')
Out[4]: [12, 43, 12.145, 546, 23, 76, 5.54, 231.1, 32]
And so everything is OK.
UPDATE:
I changed file like this:
new file a:
12 43 12.145 546 23 76 5.54 231.1 32
ad
adfad ga 235 1.12
adf a1 12 si
124 sd 1.12
and so output is like this:
In [5]: read_numbers('./a')
Out[5]: [12, 43, 12.145, 546, 23, 76, 5.54, 231.1, 32, 235, 1.12, 12, 124, 1.12]