Python 如何查找列表实例在另一个列表中是否可用?
我有两套清单Python 如何查找列表实例在另一个列表中是否可用?,python,Python,我有两套清单 list A= [(1,6),(3,10),(4,1),(0,5)] list B = [(0,3),(0,4),(30,1),(4,10)] 现在对于B中的每个项目,我必须检查它是否在列表A中可用,阈值为-2到+2 所以B中的第一个值是0,3,对于使用阈值的每一点,我发现在这个范围内,从-2到2,从1到5,列表项在列表a中是否可用。我们可以看到,最后一项值0,5满足此条件。所以我可以说项目0,3在列表A中。现在我必须把这个值放到一个新的列表中 根据流程,我的新列表将是: [(0
list A= [(1,6),(3,10),(4,1),(0,5)]
list B = [(0,3),(0,4),(30,1),(4,10)]
现在对于B中的每个项目,我必须检查它是否在列表A中可用,阈值为-2到+2
所以B中的第一个值是0,3,对于使用阈值的每一点,我发现在这个范围内,从-2到2,从1到5,列表项在列表a中是否可用。我们可以看到,最后一项值0,5满足此条件。所以我可以说项目0,3在列表A中。现在我必须把这个值放到一个新的列表中
根据流程,我的新列表将是:
[(0,3),(0,4),(4,10)]
如果有人告诉我如何做到这一点,我将非常高兴。这是我认为您需要的
A= [(1,6),(3,10),(4,1),(0,5)]
B = [(0,3),(0,4),(30,1),(4,10)]
result=[x for x in B if any(x[0]-2<=a[0]<=x[0]+2 and x[1]-2<=a[1]<=x[1]+2 for a in A)]
print(result)
您可以使用出租车几何图形:
def manhattan(as_, b):
threshold = 4
for a in as_:
p1, p2 = a
q1, q2 = b
dist = abs(p1 - q1) + abs(p2 - q2)
if dist <= threshold:
return b
else:
continue
t = list(filter(lambda i: manhattan(listA, i), listB))
[(0, 3), (0, 4), (4, 10)]
为什么?3,1也存在于listA中的阈值范围内,即4,1。对不起,这是一个错误。我已经更新了数组@Selcuknp,很高兴我能帮上忙
def manhattan(as_, b):
threshold = 4
for a in as_:
p1, p2 = a
q1, q2 = b
dist = abs(p1 - q1) + abs(p2 - q2)
if dist <= threshold:
return b
else:
continue
t = list(filter(lambda i: manhattan(listA, i), listB))
[(0, 3), (0, 4), (4, 10)]
from operator import truth
t = list(filter(truth, (manhattan(listA, i) for i in listB)))