![](/img/trans.png)
[英]How to check if a list contains all the elements of another list INCLUDING duplicates
[英]Check that list contains the elements of all the types present in another list
我有兩個Python列表: 組件和簽名 。 我想檢查簽名中列出的所有類型是否與組件列表中的至少一個元素匹配。
這里,簽名組件列表相匹配 ,因為有兩個字符串,並以組件的浮動:
signature = [float, str]
components = [1.0, [], 'hello', 1]
這里簽名 與 組件 不匹配 ,因為沒有列表類型。
signature = [float, list]
components = ['apple', 1.0]
我怎樣才能在Python 3中表達這個條件?
您可以使用all()
和any()
與嵌套生成器表達式的組合來實現此目的。 這里我使用isinstance()
來檢查signature
列表中的每個type
是否與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
。
另一種方法是計算組件中使用的類型集與簽名中的類型集之間的差異。
unique_signatures = set(signature)
components_type = set(map(type, components))
types_not_used = unique_signatures.difference(components_type)
if len(types_not_used)==0:
print('All types used')
else:
print('Types not used:', types_not_used)
我相信這個解決方案有兩個主要優點:
isinstance(1, object)
為True
:這種行為是否適合您? 使用@Moinuddin(非常好)答案提供的功能,您有以下內容:
check_match([object], [1, 2.0, 'hello'])
Out[20]: True
而我的回答是檢查object
與['int','float','str']找不到匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.