且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python,比较子列表并制作列表

更新时间:2023-11-28 23:16:52

你将不得不捕捉重复的索引,但这应该会更有效率:

You will have to catch the duplicate indexes but this should be a lot more efficient:

gr = []
it = iter(mylst)
prev = next(it)

for ind, ele in enumerate(it):
    if ele[0] == prev[0] and abs(ele[1] - prev[1]) <= 2:
        if any(abs(ele[i] - prev[i]) < 10 for i in (2, 3)):
            gr.extend((ind, ind+1))
    prev = ele

根据您的逻辑,6 和 7 不应出现,因为它们不符合条件:

Based on your logic 6 and 7 should not appear as they don't meet the criteria:

     [2, 346, 953, 995, 43], 
     [3, 346, 967, 1084, 118], 

同样要出现 10,它应该是 <= 2 而不是 <2 根据您的描述.

Also for 10 to appear it should be <= 2 not < 2 as per your description.

您可以使用 OrderedDict 删除欺骗并保持顺序:

You could use an OrderedDict to remove the dupes and keep the order:

from collections import OrderedDict

print(OrderedDict.fromkeys(gr).keys())
[0, 1, 3, 4, 10, 11, 12]