如何比较子列表python中的元素?

How to compare elements in sublist python?

如何比较python子列表中的元素?我想将索引 1 和索引 2 与其他列表进行比较。并且想要不匹配的子列表

list1 =  [['10.100.10.37', 19331, '2020-9-28 6:38:10', 15, 16], ['10.100.10.37', 29331, '2020-9-28 6:38:10', 15 ,17]]
list2 = [ ['10.100.10.37', 19331, '2020-9-28 6:38:10', 15],['10.100.10.37', 19331, '2020-9-28 9:38:10', 15],['10.100.10.37', 21301, '2020-9-28 6:38:10', 15]]


new_items = []
for item in list2:
    if not any(x[1] == item[1] for x in list1):
       if not any(x[2] != item[2] for x in list1):       
           new_items.append(item)
   
print(new_items)

我得到的输出为(实际输出):

[['10.100.10.37', 21301, '2020-9-28 6:38:10', 15]]

预期输出:

[['10.100.10.37', 19331, '2020-9-28 9:38:10', 15], 
['10.100.10.37', 21301, '2020-9-28 6:38:10', 15]]

代码中的主要问题:嵌套的 any 函数调用不会执行您想要的操作(代码不会将 list1 中每个列表的第一个和第二个索引与各自的索引进行比较list2)

中的子列表

列表理解和 any 调用就可以了:

new_items = [item for item in list2 if not any(item[1] == x[1] and item[2] == x[2] for x in list1)]

使用切片的版本(以防需要增加连续检查的次数):

new_items = [item for item in list2 if not any(item[1:3] == x[1:3] for x in list1)]

使用 filter 的替代版本(问题更直接):

tmp = [x[1:3] for x in list1]
new_items = list(filter(lambda x: not x[1:3] in tmp, list2))