Skip to main content
 首页 » 编程设计

python之如何检查列表中是否只有指定的元素

2025年05月04日23grandyang

假设我有一个这样的列表

color = ['blue', 'green', 'red', 'white', 'hurley', 'maladroit'] 

我想在这里做的是检测列表“颜色”何时只包含不是颜色的元素,即“hurley”和“maladroit”。

所以像这样:

#If the list color has at least one color in it (E.g)color = ['blue','white','maladroit'] 
    print('Nothing to see here') 
 
#If the list only consists of elements that aren't colors  
#(E.g)color = ['hurley','maladroit'] 
    print("I don't see colors.... I actually legit don't...") 

请您参考如下方法:

让我们创建一组可用颜色的集

allowed = {'blue', 'green', 'red', 'white'} 

然后检查“列表中至少有一个元素是真实颜色”的否定

print(not any(c in allowed for c in color)) 

['hurley', 'maladroit'] 返回 True,如果列表中至少有一种颜色,则返回 False

在性能方面应该非常快,因为:

  • 它正在使用set 进行测试
  • 它不是在创建其他临时列表
  • 它使用内置的 any 函数

编辑:在我们使用 set 时使用 isdisjoint 方法更简单、更快(感谢 PM 2Ring 让我知道):

print(allowed.isdisjoint(color))