Verify that the list contains items of all types present in another list.

I have two Python lists: components and signature. I want to check if all types in the signature correspond to at least one of the elements in the list of components.

Here the signature corresponds to the list of components, since the components have both a string and a float:

signature = [float, str]
components = [1.0, [], 'hello', 1]

Here the signature does not match the components because the list type is missing.

signature = [float, list]
components = ['apple', 1.0]

How can I express this condition in Python 3?

+4
source share
2 answers

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.

+7

- , , , .

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'], .

+1

Source: https://habr.com/ru/post/1693867/


All Articles