如何比较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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句