将列表合并成元组对(x,y) [英] Combine a list into tuple pairs (x, y)
本文介绍了将列表合并成元组对(x,y)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试合并通过sys.argv
传入的数字对.
示例:
I'm trying to combine pairs of numbers passed in via sys.argv
.
Example:
python myscript.py -35.12323 112.76767 -36.33345 112.76890 -33.68689 111.8980
我的目标是将它们转换为元组中的二进制数集. 像这样:
My goal would be to turn these into sets of two's in tuples. Like such:
((-35.12323,112.76767),(-36.33345,112.76890),(-33.68689,111.8980))
到目前为止,这是我一直在尝试的方法,但是当我将结果传递给Shapely Point和Polygon方法时,会遇到问题.
This is what I've tried to so far, but it has a problem when I pass the results to the Shapely Point and Polygon methods.
from shapely.geometry import Polygon
from shapely.geometry import Point
import sys
def args_to_tuple(list):
arglist = []
for coord in list:
arglist.append(float(coord))
i = 0
polylist = []
for xory in arglist:
tmp = (arglist[i],arglist[i+1])
polylist.append(tmp)
return tuple(polylist)
poly = Polygon(args_to_tuple(sys.argv[3:]))
# xy pair for point is first two sys args
point = Point(args_to_tuple(sys.argv[1:3]))
print point.within(poly) # should result in true, but doesn't
print poly.contains(point) # should result in true, but doesn't
这似乎在itertools中很常见,但是我似乎无法在该模块中找到让您成对抓取物品的任何东西.
It seems like this would be something common in itertools, but I can't seem to find anything in that module that lets you grab items in a pair.
推荐答案
In [10]: args_str = '-35.12323 112.76767 -36.33345 112.76890 -33.68689 111.8980'
In [11]: args = map(float, args_str.split())
In [12]: args
Out[12]: [-35.12323, 112.76767, -36.33345, 112.7689, -33.68689, 111.898]
In [13]: zip(args[::2], args[1::2])
Out[13]: [(-35.12323, 112.76767), (-36.33345, 112.7689), (-33.68689, 111.898)]
zip
可以替换为 itertools.izip
会产生一个迭代器而不是列表.
zip
can be replaced with itertools.izip
which produces an iterator instead of a list.
这篇关于将列表合并成元组对(x,y)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文