所以让我们假设我有这样一个列表
color = ['blue', 'green', 'red', 'white', 'hurley', 'maladroit']我在这里要做的是检测当列表'color‘仅由不是颜色的元素组成,这些元素是'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...")发布于 2017-01-06 12:46:23
让我们创建一个可用颜色的set
allowed = {'blue', 'green', 'red', 'white'}然后检查“列表中至少有一个元素是真实颜色”的否定。
print(not any(c in allowed for c in color))如果列表中至少有一种颜色,则生成True用于['hurley', 'maladroit'],False
应该表现得非常快,因为:
set来测试any函数编辑:使用isdisjoint方法更简单、更快,而我们使用的是set (TXPM2ring,用于让我知道):
print(allowed.isdisjoint(color))发布于 2017-01-06 13:09:47
灵感来自之前的答案:创建一组允许的颜色,并检查是否有任何允许的颜色在差异中。
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是最优雅的解决方案,如果你知道集合论,正如让-弗朗索瓦所指出的。
发布于 2017-01-06 13:03:29
受相关答案(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"显然,您会将此方法放入包装器中,以测试现实生活中的变量。我正在写长篇表格来演示这两种结果。
https://stackoverflow.com/questions/41506002
复制相似问题