如何解决如何比较子列表python中的元素?
如何比较python子列表中的元素?我想将索引1和索引2与其他列表进行比较。并不想匹配子列表
list1 = [['10.100.10.37',19331,'2020-9-28 6:38:10',15,16],['10.100.10.37',29331,17]]
list2 = [ ['10.100.10.37',15],'2020-9-28 9:38:10',21301,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',15]]
预期输出:
[['10.100.10.37',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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。