Python:交叉多个列表
使用多个列表时,查找它们的共同元素可能是一项有价值的操作。虽然 Python 提供了一个方便的函数来相交两个列表 (set(a).intersection(b)),但是当处理两个以上列表时,任务会变得稍微复杂一些。
让我们考虑一个场景,其中我们有一个包含多个列表的列表 d 的列表(在您的示例中,d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]])。要找到 d 中所有列表的交集,我们可以利用 Python 的集合操作和内置函数。
一种方法是重复使用 set.intersection() 方法。然而,该方法一次只能对两个集合进行操作,因此我们需要迭代地应用它。我们可以这样做:
<code class="python">intersection = set(d[0]) for lst in d[1:]: intersection = intersection.intersection(set(lst)) print(intersection) # Outputs: {3, 4}</code>
另一个简洁高效的解决方案利用 Python 的 * 运算符和 map() 函数:
<code class="python">intersection = set.intersection(*map(set, d)) print(intersection) # Outputs: {3, 4}</code>
在此解决方案中,我们使用 map( ) 函数将 d 中的每个列表转换为集合。然后 * 运算符将这个集合序列解压到 set.intersection() 的参数中,使我们能够同时找到所有集合的交集。
这两种方法都可以有效地找到存储在其中的多个列表的交集列表的列表。通过利用Python的集合运算,我们可以轻松识别任意数量的列表中的公共元素。
以上是如何在Python中查找多个列表的交集?的详细内容。更多信息请关注PHP中文网其他相关文章!