我在python中有两个列表,我想知道它们是否在同一个索引处相交。有没有一种解决这个问题的数学方法?
例如,如果我有[9,8,7,6,5]和[3,4,5,6,7],我想要一个简单有效的公式/算法,它发现在索引3处它们相交。我知道我可以进行搜索,只是想知道是否有更好的方法。
我知道有一个公式可以通过相互减去它们来解决y = mx + b形式的两条线,但我的“线”并不是真正的线,因为它仅限于列表中的项目,它可能有曲线。
感谢任何帮助。
答案 0 :(得分:4)
您可以采用两个列表中坐标的集合理论交集:
intersecting_points = set(enumerate(list1)).intersection(set(enumerate(list2)))
... enumerate为您提供了可迭代的索引和值元组 - 换句话说,(0,9),(1,8),(2,7)等。
http://docs.python.org/library/stdtypes.html#set-types-set-frozenset
......有意义吗?当然,这不会真正给你几何交集 - 例如,[1,2]在[x = 0.5,y = 1.5]与[2,1]相交 - 如果那是你想要的,那么你必须解决每个区间的线性方程式。
答案 1 :(得分:1)
from itertools import izip
def find_intersection(lineA, lineB):
for pos, (A0, B0, A1, B1) in enumerate(izip(lineA, lineB, lineA[1:], lineB[1:])):
#check integer intersections
if A0 == B0: #check required if the intersection is at position 0
return pos
if A1 == B1: #check required if the intersection is at last position
return pos + 1
#check for intersection between points
if (A0 > B0 and A1 < B1) or
(A0 < B0 and A1 > B1):
#intersection between pos and pos+1!
return pos + solve_linear_equation(A0,A1,B0,B1)
#no intersection
return None
...其中solve_linear_equation
找到了细分(0,A0)→(1,A1)
和(0,B0)→(1,B1)
之间的交集。
答案 2 :(得分:0)
我假设您的列表中有一个维度,例如[9,8,7,6,5]是x1,x2,x3,x4,x5的高度对吗?在这种情况下,您的列表将如何表示y = 0?
等曲线在任何情况下,我都不认为计算通用曲线或随机曲线的交叉点有任何捷径,最好的解决办法是进行有效的搜索。
答案 3 :(得分:0)
import itertools
def intersect_at_same_index(seq1, seq2):
return (
idx
for idx, (item1, item2)
in enumerate(itertools.izip(seq1, seq2))
if item1 == item2).next()
这将返回两个序列具有相同项目的索引,如果所有项目对不同,则返回StopIteration
。如果您不喜欢这种行为,请将return语句包含在try语句中,并在except StopIteration
子句中返回您最喜欢的失败指示符(例如-1,None ...)