2017-01-06 43 views
1

所以可以说我有这样的如何检查是否只有指定的元素保留在列表中?

color = ['blue', 'green', 'red', 'white', '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...") 
+0

列出颜色并对其进行过滤。 –

+0

https://www.tcl.tk/man/tcl8.4/TkCmd/colors.htm –

+0

哦,不,这些颜色只是我用于此代码的示例,如果这是误导性的,则很抱歉。我会研究过滤方法,谢谢。 –

回答

2

让我们创建可选颜色

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

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

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

得率True对于['hurley', 'maladroit'],False,如果有至少在列表中选择颜色

应该是非常快速的性能,明智的,因为:

  • 它使用set测试
  • 它不是创建其他临时列表
  • 它使用内置-in any功能

编辑:更简单和使用,同时我们使用更快isdisjoint方法一个set(THX PM 2Ring让我找到了):

print(allowed.isdisjoint(color)) 
+1

有一个方法来测试相交... –

+0

至少'集合'存在:)谢谢。没有花时间挖掘出来。 –

+0

这看起来很有意思,会调查一下并且玩弄它,谢谢。 –

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

你可以结合这两个

color.count('hurley') 
color.count('maladroit') 

或 这些

'hurley' in color 
'maladroit' in color 
+0

如果该列表拥有一百万个条目,该怎么办? –

+0

的大量物品 的'code' 高清相交(A,B): 返回列表(集(一)设置(B)) 打印相交(颜色,allowedcolor) 'code' – crowchirp

1

由相关答案启发(https://stackoverflow.com/a/642919/2034487),您可以使用set()intersection()方法:含有颜色

列表:

$ approved_colours = set(['blue','green']) 
$ list_with_colours = ['blue', 'green', 'red', 'white', 'hurley', 'maladroit'] 
$ if approved_colours.intersection(list_with_colours): 
$  print("There are colours present") 
$ else: 
$  print("There are no colours present") 
> "There are colours present" 

做同样没有任何任何颜色:

$ list_without_colours = ['hurley', 'maladroit'] 
$ if approved_colours.intersection(list_without_colours): 
$  print("There are colours present") 
$ else: 
$  print("There are no colours present") 
> "There are no colours present" 

很明显,你会把这种方法为包装,以测试在现实生活中的一个变量。我正在写长表格来展示两个结果。

+0

学习了很多关于该答案的交集函数。不知道这样的事情是否存在,也会对此进行测试。谢谢! –

2

受以前答案的启发: 创建一组允许的颜色并检查是否有任何允许的颜色存在差异。

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

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

color_set = set(color) 
if len(color_set - allowed_colors) < len(color_set): 
    print('Nothing to see here') 
else: 
    print("I don't see colors.... I actually legit don't...") 

编辑:解决方法是不正确的。现在按预期工作。尽管isdisjoint是最优雅的解决方案,但如Jean-François指出的那样,如果您知道集合论。

+0

您可以通过跳过一行并在其前面放置4个空格来编写代码块,您希望开始编写代码。更好的格式化方法,只是让您知道:) –

+0

'if set(color) - allowed_colors: '就够了,不需要调用'len' –

相关问题