Home > Mobile >  Extract floats from list of list of strings
Extract floats from list of list of strings

Time:09-23

[['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]

How to extract what's in between the parentheses as floats. The output should be something like this:

[[25, 32], [24.2, 31.5], [22, 34], [20.5, 34]]

CodePudding user response:

Converting a tuple to a list after extracting the tuple from the strings will consume a lot of memory and is not ideal. If you just want to get the strings of the tuple into floating numbers. You can first do a str.split and eval

[eval(j.split('. ')[1]) for i in alist for j in i]
[(25, 32), (24.2, 31.5), (22, 34), (20.5, 34)]

CodePudding user response:

If your input is always in this format, you can do:

your_input = [['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]
output = [[float(number) for number in elem[0].split(". ")[1].rstrip(")").lstrip("(").split(", ")] for elem in your_input]

output:

[[25.0, 32.0], [24.2, 31.5], [22.0, 34.0], [20.5, 34.0]]
  • Related