首页 > 解决方案 > 在另一个列表的嵌套列表中比较/查找列表

问题描述

我有几个名为find. 我想知道这些find是否是full_list. 列表find 1-4是一部分,full_list而列表find 5-7不是。

下面的示例返回"Yes".

find1 = [[1, 1]]
find2 = [[1, 1], [2, 2]]
find3 = [[1, 1], [3, 3]]
find4 = [[4, 4], [2, 2], [3, 3]]

find5 = [[1, 0]]
find6 = [[1, 1], [2, 0]]
find7 = [[1, 1], [3, 0]]

full_list = [[1, 1], [2, 2], [3, 3], [4, 4]]

if find2[0] in full_list and find2[1] in full_list:
    print("Yes")
else:
    print("No")

因为len(find2) != len(find4),当前的if语句非常笨拙,几乎没有用处。

如何使这项工作以更普遍的方式工作?

标签: pythonpython-3.xlistnested-lists

解决方案


You could use all() with a generator which returns a True if everything is a truthy or False:

if all(x in full_list for x in find2):
    print("Yes")
else:
    print("No")

# => prints Yes

This one is generic, just need to change find2 to any list you need to check with full_list.


推荐阅读