Python Forum
Can't find a library for this
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can't find a library for this
#1
I needed code that converted a string into a list of floats, where the string is in the format or '1, 2, .5, 6, 1.23, 10' etc and then the list would be [1, 2, .5, 6, 1.23, 10]
The code I made works but there must be some sort of library that does this, right?
placeholder2=''
x_list=[]
line=[1, 3, .5, 10, -1.23]
for j in line: # line is the string
    if j!=',':
        placeholder+=j # placeholder is the same string but with no commas
placeholder2=placeholder.split() # placeholder 2 a list of the strings of the numbers I want
for i in placeholder2:
    x_list.append(float(i)) #x_list is the output, the list of integers
print(x_list)
I needed this code because I had to put a list of integers into a line of a csv file, then take that line out in another program and use each number for a calculation.
Reply
#2
I would str.split on ", " and then use either a comprehension or a map to convert the list generated by split into from strings to floats. Should be a simple one-liner.
Reply
#3
This can be solved with functional programming very clean and easy.

numbers = 1, 2, 3, 4 # it's tuple, but you can use also any iterable (list etc.)
floats = list(map(float, numbers))
The function map returns an an iterator. The function float is applied on each element of numbers. The functions list, tuple, dict, set etc. are consuming iterators/iterables. In this case it's the map object. If you just execute the map function, nothing is evaluated. This is also good for data, which is bigger than your memory.

if you unroll the example, the code looks like this:

new_list = []
for n in number in numbers:
    new_list.append(float(n))
The only big problem is, that you don't have exception handling with the previous example (maybe with some nasty tricks).
The unrolled example can handle exceptions. For example when your list has an object inside, which can't converted to a float. It will raise a ValueError. You can catch this error and decide what you want to do.

Written on a small cell phone. Sorry for typos.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020