0

I have two strings variables:

data = "14.816,-83.828,14.878,-83.710,14.878,-83.628,14.918,-83.579,15.014,-83.503"
adata = "8.036,-82.900,8.109,-82.886,8.163,-82.909,8.194,-82.913,8.208,-82.936"

I want to split each variable data with a , but every two , and then take the result and add it to a list poly.

At the end, I want my list like this:

poly = [(14.816,-83.828),(14.878,-83.710),(14.878,-83.628),(14.918,-83.579),(15.014,-83.503),(8.036,-82.900),(8.109,-82.886),(8.163,-82.909),(8.194,-82.913),(8.208,-82.936)]

Is there any easy way to do this in python?

Weafs.py
  • 22,731
  • 9
  • 56
  • 78
robe007
  • 3,523
  • 4
  • 33
  • 59

3 Answers3

4

You could use the grouper recipe, zip(*[iterator]*2) to group the items in pairs:

In [151]: zip(*[iter(map(float, data.split(',')+adata.split(',')))]*2)
Out[151]: 
[(14.816, -83.828),
 (14.878, -83.71),
 (14.878, -83.628),
 (14.918, -83.579),
 (15.014, -83.503),
 (8.036, -82.9),
 (8.109, -82.886),
 (8.163, -82.909),
 (8.194, -82.913),
 (8.208, -82.936)]

To extend poly in a loop:

for ...:
    poly.extend(zip(*[iter(map(float, data.split(',')))]*2))
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Ok, works ! But, what happens if i have only the variable **data** inside a **for** statment, and it's value changes on each iteration? And on each iteration i want to have the same result, i mean, add it to a unique **poly** list. – robe007 Aug 29 '14 at 22:33
1

Since you're on python2.x, you can use the fact that map can take an arbitrary number of iterables:

>>> map(lambda x,y: (float(x), float(y)), data.split(','), adata.split(','))
[(14.816, 8.036), (-83.828, -82.9), (14.878, 8.109), (-83.71, -82.886), (14.878, 8.163), (-83.628, -82.909), (14.918, 8.194), (-83.579, -82.913), (15.014, 8.208), (-83.503, -82.936)]

I think this is neat -- I don't really recommend that you use this as it isn't forward compatible with python3.x...

I suppose the py3.x variant would be:

map(lambda t: (float(t[0]), float(t[1])), zip(data.split(','), adata.split(',')))
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

If the input data is reasonably well formatted, you could always resort to a use of eval and zip, as such:

data = "14.816,-83.828,14.878,-83.710,14.878,-83.628,14.918,-83.579,15.014,-83.503"
data = "[" + data + "]"
poly = [(x, y) for x, y in zip(eval(data)[::2], eval(data)[1::2])]

Or to get both data and adata:

data = "14.816,-83.828,14.878,-83.710,14.878,-83.628,14.918,-83.579,15.014,-83.503"
adata = "8.036,-82.900,8.109,-82.886,8.163,-82.909,8.194,-82.913,8.208,-82.936"
data = "[" + data + "," + adata + "]"
poly = [(x, y) for x, y in zip(eval(data)[::2], eval(data)[1::2])]
therealrootuser
  • 10,215
  • 7
  • 31
  • 46