robe007
robe007

Reputation: 3947

Split strings every two places and add it to a list

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?

Upvotes: 0

Views: 110

Answers (3)

unutbu
unutbu

Reputation: 880977

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))

Upvotes: 4

mgilson
mgilson

Reputation: 310297

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(',')))

Upvotes: 1

therealrootuser
therealrootuser

Reputation: 10924

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])]

Upvotes: 0

Related Questions