Mahdi
Mahdi

Reputation: 807

Convert a string to an array

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

Answers (3)

Mykola Zotko
Mykola Zotko

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

Austin
Austin

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

Azat Ibrakov
Azat Ibrakov

Reputation: 10963

Assuming that you are using dot for separating decimal part from fractional one (and commas are not needed) we can

  1. Remove commas in string.
  2. Split string by whitespace.
  3. Convert each of substrings to floating number.
  4. 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

Related Questions