如何在Python中测试一个列表是否包含另一个具有特定项的列表?
我有一个列表,想检查它是否已经包含一个特定项目的列表 从这个例子中,一切都应该很清楚:如何在Python中测试一个列表是否包含另一个具有特定项的列表?,python,list,sorting,Python,List,Sorting,我有一个列表,想检查它是否已经包含一个特定项目的列表 从这个例子中,一切都应该很清楚: list = [[1,2],[3,4],[4,5],[6,7]] for test in [[1,1],[1,2],[2,1]]: if test in list: print True else: print False #Expected: # False # True # True #Reality: # False #
list = [[1,2],[3,4],[4,5],[6,7]]
for test in [[1,1],[1,2],[2,1]]:
if test in list:
print True
else:
print False
#Expected:
# False
# True
# True
#Reality:
# False
# True
# False
是否有一个函数可以比较列表中的项目,而不管它们是如何排序的?您想要使用的是一个集合:
set([1,2])==set([2,1])
返回True
所以
也返回True。如果它们确实是集合,请使用集合类型
# This returns True
set([2,1]) <= set([1,2,3])
#返回True
set([2,1])如果你想得到[1,2]=[2,1],你不应该使用list。Set是正确的类型。在列表中,组件的顺序很重要,而在集合中则不重要。这就是为什么你不能得到“False-True-True”的原因。可能重复的[使用Python在另一个列表中搜索列表的值](),用于在…中进行测试:在列表中打印排序(测试)顺便说一句,在Python3中--这可能是下一代人实际上能够使用的--你可以说[{1,2},{3,4},{4,5},{6,7}]
。
# This returns True
set([2,1]) <= set([1,2,3])