Ash*_*ley 4 python types list python-3.x
我有两个Python列表:组件和签名.我想检查签名中列出的所有类型是否与组件列表中的至少一个元素匹配.
在这里,签名匹配的组件列表,因为那里既是字符串,并以浮动组件:
signature = [float, str]
components = [1.0, [], 'hello', 1]
Run Code Online (Sandbox Code Playgroud)
这里签名 与 组件不匹配,因为没有列表类型.
signature = [float, list]
components = ['apple', 1.0]
Run Code Online (Sandbox Code Playgroud)
我怎样才能在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)
Run Code Online (Sandbox Code Playgroud)
样品运行:
# 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
Run Code Online (Sandbox Code Playgroud)
说明:上面嵌套的生成器表达式由两部分组成.第一部分是:
all(...`any()` call... for s in signature)
Run Code Online (Sandbox Code Playgroud)
在这里,我迭代signature
列表以获取其中的每个元素s
.all()
将返回True
只有当所有的...any() call...
逻辑将返回True
.否则它会回来False
.
第二个是...any() call...
生成器表达式:
any(isinstance(c, s) for c in components)
Run Code Online (Sandbox Code Playgroud)
在这里,每个元素c
在components
列表中,我检查的类型是否c
是s
从外部产生理解.如果任何类型匹配,any(..)
将返回True
.如果没有c
匹配条件,any(...)
将返回False
.