gpt4 book ai didi

Python:比较两个列表的更好方法?

转载 作者:太空宇宙 更新时间:2023-11-04 08:44:00 25 4
gpt4 key购买 nike

请不要给我负号。我想问一个更好的方法来解决这个问题,因为我现在所做的正在成为我的巨大负担。

这是我的问题:我有两个列表。我想确保一个列表中的任何项目都不在另一个列表中。

在 Python 中,我一直在处理以下几行...(假设 List_s 有 3 个项目。)

if List_s[0] not in List_big and List_s[1] not in List_big and List_s[2] not in List_big:   #none item from List_s should be in List_big
do something
else:
pass

这些行对我来说实际上还可以,直到我突然意识到我必须处理长度大于 200 的列表。我有很多列表可以比较。

那么我该如何更改代码呢?非常感谢您的帮助!

最佳答案

您可以将其中一个列表转换为集合 并使用set.intersection :

if not set(List_s).intersection(List_big):
print('no common items between lists')

注意两个列表中的元素必须是hashable .

关于Python:比较两个列表的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com