*Memo:
chain() and chain.from_iterable() can return the iterator which returns the elements of chained *iterables and iterable respectively one by one as shown below:
*Memo for chain():
- The 1st arguments are
*iterables(Optional-Default:()-Type:Iterable):- Don't use any keywords like
*iterables=,iterables=, etc.
- Don't use any keywords like
*Memo for chain.from_iterable():
- The 1st argument is
iterable(Required-Type:Iterable):- Don't use
iterable=.
- Don't use
from itertools import chain
v = chain()
v = chain('')
v = chain('', '')
v = chain([])
v = chain([], [])
v = chain.from_iterable('')
v = chain.from_iterable([])
print(v)
# <itertools.chain object at 0x0000026906CEAD70>
print(next(v))
# StopIteration:
from itertools import chain
v = chain('ABCDEF')
v = chain('ABC', 'DE', 'F')
v = chain(['A', 'B', 'C', 'D', 'E', 'F'])
v = chain(['A', 'B', 'C'], ['D', 'E'], ['F'])
v = chain.from_iterable('ABCDEF')
v = chain.from_iterable(['A', 'B', 'C', 'D', 'E', 'F'])
print(next(v)) # A
print(next(v)) # B
print(next(v)) # C
print(next(v)) # D
print(next(v)) # E
print(next(v)) # F
print(next(v)) # StopIteration:
from itertools import chain
for x in chain('ABCDEF'):
# for x in chain('ABC', 'DE', 'F'):
# for x in chain(['A', 'B', 'C', 'D', 'E', 'F']):
# for x in chain(['A', 'B', 'C'], ['D', 'E'], ['F']):
# for x in chain.from_iterable('ABCDEF'):
# for x in chain.from_iterable(['A', 'B', 'C', 'D', 'E', 'F']):
print(x)
# A
# B
# C
# D
# E
# F
compress() can return the iterator which returns the elements of data one by one if the corresponding elements of selectors are True as shown below:
*Memo:
- The 1st argument is
data(Required-Type:Iterable). - The 2nd argument is
selectors(Required-Type:Iterable):- It selects elements from
data.
- It selects elements from
from itertools import compress
v = compress(data='', selectors=[])
v = compress(data=[], selectors=[])
print(v)
# <itertools.compress object at 0x0000026905F8CF10>
print(next(v))
# StopIteration:
from itertools import compress
v = compress(data='ABCDE', selectors=[1, 0, 1, 1, 0])
v = compress(data=['A', 'B', 'C', 'D', 'E'], selectors=[1, 0, 1, 1, 0])
print(next(v)) # A
print(next(v)) # C
print(next(v)) # D
print(next(v)) # StopIteration:
from itertools import compress
for x in compress(data='ABCDE', selectors=[1, 0, 1, 1, 0]):
# for x in compress(data=['A', 'B', 'C', 'D', 'E'],
# selectors=[1, 0, 1, 1, 0]):
print(x)
# A
# C
# D
from itertools import compress
for x in compress(data='ABCDE', selectors=[1, 0, 1, 1, 0, 1, 1, 1]):
# for x in compress(data=['A', 'B', 'C', 'D', 'E'],
# selectors=[1, 0, 1, 1, 0, 1, 1, 1]):
print(x)
# A
# C
# D
from itertools import compress
for x in compress(data='ABCDE', selectors=[1, 0, 1]):
# for x in compress(data=['A', 'B', 'C', 'D', 'E'], selectors=[1, 0, 1]):
print(x)
# A
# C
Top comments (0)