Reputation: 807
I have a string as follows
144.963286 -37.814212 144.964498 -37.813854 144.964962 -37.814806 144.963711, -37.815168
I want to convert above string to an array such as below:
[(144.963286, -37.814212), (144.964498, -37.813854), (144.964962, -37.814806), (144.963711, -37.815168)]
Upvotes: 0
Views: 131
Reputation: 17794
You can use regex:
import re
s = '144.963286 -37.814212 144.964498 -37.813854 144.964962 -37.814806 144.963711, -37.815168'
pattern = r'(-?\d+\.\d+).+?(-?\d+\.\d+)'
new_s = [(float(i.group(1)), float(i.group(2))) for i in re.finditer(pattern, s)]
# [(144.963286, -37.814212), (144.964498, -37.813854), (144.964962, -37.814806), (144.963711, -37.815168)]
Upvotes: 0
Reputation: 26039
Use zip
with slicing:
s = '144.963286 -37.814212 144.964498 -37.813854 144.964962 -37.814806 144.963711 -37.815168'
splitted = s.split()
result = list(zip(splitted[::2], splitted[1::2]))
# [('144.963286', '-37.814212'), ('144.964498', '-37.813854'), ('144.964962', '-37.814806'), ('144.963711', '-37.815168')]
Upvotes: 2
Reputation: 10963
Assuming that you are using dot for separating decimal part from fractional one (and commas are not needed) we can
zip
floats into pairs.like
>>> string = '144.963286 -37.814212 144.964498 -37.813854 144.964962 -37.814806 144.963711, -37.815168'
>>> floats = map(float, string.replace(',', '').split()) # use `itertools.imap` instead of `map` in Python2
>>> list(zip(floats, floats))
[(144.963286, -37.814212), (144.964498, -37.813854), (144.964962, -37.814806), (144.963711, -37.815168)]
As @AlexanderReynolds suggested we can use itertools.zip_longest
function instead of zip
for cases with odd number of arguments with some sort of fillvalue
(default is None
) like
>>> string = '144.963286, -37.814212 42'
>>> floats = map(float, string.replace(',', '').split())
>>> from itertools import zip_longest
>>> list(zip_longest(floats, floats,
fillvalue=float('inf')))
[(144.963286, -37.814212), (42.0, inf)]
also we can do it in one (pretty complex though) line with itertools.repeat
like
>>> from itertools import repeat
>>> list(zip_longest(*repeat(map(float, string.replace(',', '').split()),
times=2),
fillvalue=float('inf')))
[(144.963286, -37.814212), (42.0, inf)]
Upvotes: 4