【发布时间】:2025-11-26 17:45:01
【问题描述】:
我有一大堆排序的子列表,其中包含如下列表:
biglist = [
[[25368, 22348], [22348, 21234], [21230, 17750], [17754, 15924], [15924, 14490],[14491, 12780]]
[[22390, 21242], [10140, 4260], [4260, 2686], [2686, 438]],
[[14044, 8726], [8762, 4144], [4144, 1420]],
[[5817, 5097], [5590, 5530], [5304, 2729], [5097, 4430], [3450, 2489], [2729, 1676] , [2489, 1618]]
]
对于每个子列表 - 理想情况下,
for sublist in biglist:
for i, element in enumerate(sublist):
abs(element[i][1] - element [i+1][0]) < 10
例如,子列表[[25368, 22348], [22348, 21234], [21230, 17750], [17754, 15924], [15924, 14490], [14491, 12780] 没有任何问题,因为:
22348 - 22348 = 0
21234 - 21230 = 4
17750 - 17754 = 4
15924 - 15924 = 0
14490 - 14491 = 1
所以,如果上述条件 (abs(element[i][1] - element [i+1][0])
例如,在子列表中
[[5817, 5097], [5590, 5530], [5304, 2729], [5094, 4430], [3450, 2489], [2729, 1676], [2489, 1618]]
代码应该打印如下内容:
[5817,5097] matches [5094, 4430] within tolerance of 10 - skipped elements: [5590, 5530], [5304, 2729]
[5304, 2729] matches [2729, 1676] within tolerance of 10 - skipped elements: [5094, 4430], [3450, 2489]
[3450, 2489] matches [2489, 1618] within tolerance of 10 - skipped elements: [2729, 1676]
如果根本找不到匹配项,则打印:[5590, 5530] has no match
回答:
我似乎得到了我想要的结果:
for sublist in biglist:
for i, element in list(enumerate(sublist))[:-1]:
found = False
if abs(sublist[i][1] - sublist[i+1][0]) > 10:
for j in range(i+1, len(sublist)):
if abs(sublist[i][1] - sublist[j][0]) < 10:
print(sublist[i], "matches", sublist[j], "within tolerance of 10 - skipped elements:", sublist[i+1:j])
found = True
break
if not found:
print(sublist[i], "has no matches")
但是has no matches 给了我错误的结果:
[22390, 21242] has no matches
[14044, 8726] has no matches
[5817, 5097] matches [5097, 4430] within tolerance of 10 - skipped elements: [[5590, 5530] [5304, 2729]]
[5590, 5530] has no matches
[5304, 2729] matches [2729, 1676] within tolerance of 10 - skipped elements: [[5097, 4430], [3450, 2489]]
[5097, 4430] has no matches
[3450, 2489] matches [2489, 1618] within tolerance of 10 - skipped elements: [[2729, 1676]]
[2729, 1676] has no matches
【问题讨论】:
-
您可以使用
scipy.spatial.KDTree加快速度,仅供参考。
标签: python-3.x list indexing