我有两个字符串变量:
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"
我希望使用,
分割每个变量数据,但每两个,
,然后将结果添加到列表poly
。
最后,我希望我的列表如下:
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)]
在python中有没有简单的方法呢?
答案 0 :(得分:4)
您可以使用grouper recipe,zip(*[iterator]*2)
成对分组项目:
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)]
循环中的extend poly
:
for ...:
poly.extend(zip(*[iter(map(float, data.split(',')))]*2))
答案 1 :(得分:1)
由于你使用的是python2.x,你可以使用map
可以接受任意数量的迭代的事实:
>>> 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)]
我认为这很整洁 - 我不建议你使用它,因为它不能与python3.x向前兼容......
我认为py3.x变体是:
map(lambda t: (float(t[0]), float(t[1])), zip(data.split(','), adata.split(',')))
答案 2 :(得分:0)
如果输入数据格式合理,您可以随时使用eval
和zip
,这样:
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])]
或同时获得data
和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])]