我有两个Python列表:components和signature。我想检查签名中列出的所有类型是否都至少与组件列表中的元素之一匹配。
在这里,签名匹配的组件列表,因为那里既是字符串,并以浮动组件:
signature = [float, str]
components = [1.0, [], 'hello', 1]
此处,签名 与 components不匹配,因为没有列表类型。
signature = [float, list]
components = ['apple', 1.0]
如何在Python 3中表达这种情况?
您可以结合使用all()
和any()
嵌套生成器表达式来实现此目的。在这里我使用的isinstance()
检查每一个type
你signature
在对象列表中匹配components
列表。使用此功能,您的自定义函数将为:
def check_match(signature, components):
return all(any(isinstance(c, s) for c in components) for s in signature)
样品运行:
# Example 1: Condition is matched - returns `True`
>>> signature = [str, int]
>>> components = [1, 'hello', []]
>>> check_match(signature, components)
True
# Example 2: Condition is not matched - returns `False`
>>> signature = [float, list]
>>> components = ['apple', 1.0]
>>> check_match(signature, components)
False
说明:上面的嵌套生成器表达式由两部分组成。第一部分是:
all(...`any()` call... for s in signature)
在这里,我正在迭代signature
列表以使其中包含每个元素s
。仅当所有逻辑都all()
将返回True
时才...any() call...
返回True
。否则它将返回False
。
其次是...any() call...
生成器表达式为:
any(isinstance(c, s) for c in components)
在这里,每个元素c
在components
列表中,我检查的类型是否c
是s
从外部产生理解。如果任何类型匹配,any(..)
将返回True
。如果不c
符合条件,any(...)
将返回False
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句