我有一张纬度的清单,拉茨。我试图比较每个纬度和其他纬度,并找到每个组合的列表项目,在0.01范围内彼此。但是,我目前拥有的代码就是这样做的,它还将每个列表值与其自身进行比较。
lats = [79.826, 79.823, 79.855, 79.809]
for i in lats:
for j in lats:
if (i - 0.1) <= j <= (i + 0.1):
print(str(i) +" and "+ str(j))这将返回输出:
79.826 and 79.826
79.826 and 79.823
79.826 and 79.855
79.826 and 79.809
79.823 and 79.826
79.823 and 79.823
79.823 and 79.855
79.823 and 79.809
79.855 and 79.826
79.855 and 79.823
79.855 and 79.855
79.855 and 79.809
79.809 and 79.826
79.809 and 79.823
79.809 and 79.855
79.809 and 79.809发布于 2022-08-05 15:03:01
您正在隐式计算跨乘积;您可以编写
for i, j in itertools.product(lats, repeat=2):
if i - 0.1 <= j <= 1 + 0.1:
...而不是。但是,您想要的是列表中的两个元素组合:
for i, j in itertools.combinations(lats, 2):发布于 2022-08-05 15:15:29
为了迭代和生成lats组合,虽然itertools解决方案应该是首选的方法,但您可能对“手工编写”这种编码方式感兴趣。假设您真正想要的只是任意顺序的任意两个lats,而不是重复的两个,那么您可以简单地逐步限制第二个循环:
for i, x in enumerate(lats):
for y in lats[i + 1:]:
...而且,当前编写的条件比需要的要复杂一些。您真正想要的是,两个值x和y都小于某个值d,因此您可以编写条件:
(x - d) <= y <= (x + d):作为:
abs(x - y) <= d发布于 2022-08-05 15:10:23
这里有使用itertools.combinations和abs的简洁版本。
from itertools import combinations
lats = [79.826, 79.823, 79.855, 79.809]
print([c for c in combinations(lats, 2) if abs(c[0] - c[1]) > 0.01])这意味着:
[(79.826, 79.855), (79.826, 79.809), (79.823, 79.855), (79.823, 79.809), (79.855, 79.809)]或者使用格式:
from itertools import combinations
lats = [79.826, 79.823, 79.855, 79.809]
close_lats = [c for c in combinations(lats, 2) if abs(c[0] - c[1]) > 0.01]
for combo in close_lats:
print(f"{combo[0]} and {combo[1]}")给予:
79.826 and 79.855
79.826 and 79.809
79.823 and 79.855
79.823 and 79.809
79.855 and 79.809顺便提一下,您的问题是,您寻找的是0.01以内的彼此,但您的代码示例看起来似乎在0.1或彼此之间。
https://stackoverflow.com/questions/73251733
复制相似问题