如何检查元组或列表中的所有元素是否在另一个中?

2022-01-17 00:00:00 python list set tuples

问题描述

例如,我想检查元组 (1, 2) 中的每个元素是否在元组 (1, 2, 3, 4, 5) 中.我不认为使用循环是一种好方法,我认为它可以在一行中完成.

For example, I want to check every elements in tuple (1, 2) are in tuple (1, 2, 3, 4, 5). I don't think use loop is a good way to do it, I think it could be done in one line.


解决方案

你可以使用set.issubsetset.issuperset 检查一个元组或列表中的每个元素是否在另一个中.

You can use set.issubset or set.issuperset to check if every element in one tuple or list is in other.

>>> tuple1 = (1, 2)
>>> tuple2 = (1, 2, 3, 4, 5)
>>> set(tuple1).issubset(tuple2)
True
>>> set(tuple2).issuperset(tuple1)
True

相关文章