我刚开始学习python,我需要解决这个问题,但我卡住了。我们已经得到一个函数(lSegInt)来查找线的交点。我需要做的是正确地格式化数据,以便通过这个函数来传递数据,找出两条多段线相交的时间。从Python列表中计算线交点
这里的数据:
pt1 = (1,1)
pt2 = (5,1)
pt3 = (5,5)
pt4 = (1,5)
pt5 = (2,2)
pt6 = (2,3)
pt7 = (4,6)
pt8 = (6,3)
pt9 = (3,1)
pt10 = (1,4)
pt11 = (3,6)
pt12 = (4,3)
pt13 = (7,4)
l5 = [[pt1, pt5, pt6, pt7, pt8, pt9]]
l6 = [[pt10, pt11, pt12, pt13]]
这里是我的代码:
def split(a):
lines = []
for i in range(len(a[0]) - 1):
line = []
for j in (i,i+1):
line.append(a[0][j])
lines.append(line)
return lines
sl5 = split(l5)
sl6 = split(l6) + split(l6)
这是我很坚持。需要找出多段折线相交的次数。我想为sl5和sl6使用压缩for循环,但它不会检查一个列表的每一行与另一列表的每一行,并且列表的长度也不同。
while i < len(sl5):
for x, in a,:
z = 1
fresults.append(lSegInt(x[0],x[1],sl6[0][0],sl6[1][0]))
fresults.append(lSegInt(x[0],x[1],sl6[1][0],sl6[1][1]))
fresults.append(lSegInt(x[0],x[1],sl6[2][0],sl6[2][1]))
i = i + 1
print fresults
功能:
def lSegInt(s1, s2, t1, t2):
'''Function to check the intersection of two line segments. Returns
None if no intersection, or a coordinate indicating the intersection.
An implementation from the NCGIA core curriculum. s1 and s2 are points
(e.g.: 2-item tuples) marking the beginning and end of segment s. t1
and t2 are points marking the beginning and end of segment t. Each point
has an x and y coordinate: (1, 3).
Variables are named following linear formula: y = a + bx.'''
if s1[0] != s2[0]: # if s is not vertical
b1 = (s2[1] - s1[1])/float(s2[0] - s1[0])
if t1[0] != t2[0]: # if t is not vertical
b2 = (t2[1] - t1[1])/float(t2[0] - t1[0])
a1 = s1[1] - (b1 * s1[0])
a2 = t1[1] - (b2 * t1[0])
if b1 == b2: # if lines are parallel (slopes match)
return(None)
xi = -(a1-a2)/float(b1-b2) # solve for intersection point
yi = a1 + (b1 * xi)
else:
xi = t1[0]
a1 = s1[1] - (b1 * s1[0])
yi = a1 + (b1 * xi)
else:
xi = s1[0]
if t1[0] != t2[0]: # if t is not vertical
b2 = (t2[1] - t1[1])/float(t2[0] - t1[0])
a2 = t1[1] - (b2 * t1[0])
yi = a2 + (b2 * xi)
else:
return(None)
# Here is the actual intersection test!
if (s1[0]-xi)*(xi-s2[0]) >= 0 and \
(s1[1]-yi)*(yi-s2[1]) >= 0 and \
(t1[0]-xi)*(xi-t2[0]) >= 0 and \
(t1[1]-yi)*(yi-t2[1]) >= 0:
return((float(xi), float(yi))) # Return the intersection point.
else:
return(None)
任何帮助是极大的赞赏。对不起,文字墙。
是重要的顺序? – 2014-10-02 00:32:31