python – 比较两个点元组列表的更快方法?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 比较两个点元组列表的更快方法?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1493字,纯文字阅读大概需要3分钟。
内容图文
![python – 比较两个点元组列表的更快方法?](/upload/InfoBanner/zyjiaocheng/719/ce5a187227764bd792b6d49e90a14405.jpg)
我有两个列表(可能是也可能不是相同的长度).在每个列表中,是一系列两个点的元组(基本上是X,Y值).
我将两个列表相互比较,找到两个具有相似点值的点.我已经尝试过列表理解技术,但它对列表中的嵌套元组感到困惑,我无法让它工作.
这是最好(最快)的方式吗?我觉得可能有更多的Pythonic方式来做这件事.
说我有两个清单:
pointPairA = [(2,1), (4,8)]
pointPairB = [(3,2), (10,2), (4,2)]
然后是用于存储对的空列表和容差值以仅存储匹配的对
matchedPairs = []
tolerance = 2
然后这个解包元组的循环,比较差异,并将它们添加到matchedPairs列表以指示匹配.
for pointPairA in pointPairListA:
for pointPairB in pointPairListB:
## Assign the current X,Y values for each pair
pointPairA_x, pointPairA_y = pointPairA
pointPairB_x, pointPairB_x = pointPairB
## Get the difference of each set of points
xDiff = abs(pointPairA_x - pointPairB_x)
yDiff = abs(pointPairA1_y - pointPairB_y)
if xDiff < tolerance and yDiff < tolerance:
matchedPairs.append((pointPairA, pointPairB))
这会导致matchesPairs看起来像这样,里面有两个点元组的元组:
[( (2,1), (3,2) ), ( (2,1), (4,2) )]
解决方法:
这里pointpairA是单个列表,pointpairB将是20k的列表之一
from collections import defaultdict
from itertools import product
pointPairA = [(2,1), (4,8)]
pointPairB = [(3,2), (10,2), (4,2)]
tolerance = 2
dA = defaultdict(list)
tolrange = range(-tolerance, tolerance+1)
for pA, dx, dy in product(pointPairA, tolrange, tolrange):
dA[pA[0]+dx,pA[1]+dy].append(pA)
# you would have a loop here though the 20k lists
matchedPairs = [(pA, pB) for pB in pointPairB for pA in dA[pB]]
print matchedPairs
内容总结
以上是互联网集市为您收集整理的python – 比较两个点元组列表的更快方法?全部内容,希望文章能够帮你解决python – 比较两个点元组列表的更快方法?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。