簡體   English   中英

檢查該列表是否包含另一個列表中存在的所有類型的元素

[英]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)

在這里,每個元素ccomponents列表中,我檢查的類型是否cs從外部產生理解。 如果任何類型匹配,則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)

我相信這個解決方案有兩個主要優點:

  1. 如果您的組件列表很長且有許多重復類型,那么效率會更高,因為您減少了比較次數
  2. 你想要在課堂上匹配的精確程度如何? 子類應該通過測試嗎? 例如, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM