Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the function return each element of the list on a new line?

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
enter image description here

and i’m wondering why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading