比较Python嵌套列表 [英] Comparing Python nested lists

查看:230
本文介绍了比较Python嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个嵌套列表,每个嵌套列表都包含两个字符串,例如:

I have two nested lists, each nested list containing two strings e.g.:

list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')]

我想比较两个列表并恢复那些彼此相同的嵌套列表.在这种情况下,将仅返回('DEF','[2,3,4]').列表可能会很长.有没有一种有效的方法可以做到这一点?

I would like to compare the two lists and recover those nested lists which are identical with each other. In this case only ('DEF','[2,3,4]') would be returned. The lists could get long. Is there an efficient way to do this?

推荐答案

如果列表仅包含字符串元组,那么最简单的方法是使用集合交集(&):

If the lists only contain string tuples, then the easiest way to do it is using sets intersection (&):

>>> set([('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')]) & set([('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')])
set([('DEF', '[2,3,4]')])

这篇关于比较Python嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆