比较Python嵌套列表

And*_*ndy 3 python nested intersection list

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

list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')]
Run Code Online (Sandbox Code Playgroud)

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

Nad*_*mli 8

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]')])
Run Code Online (Sandbox Code Playgroud)