Bit*_*han 7 python python-itertools python-3.x
我正在学习itertools模块,我试图让迭代器从作为输入提供的iterables中返回每个元素.
Agruments Results
p, q, … p0, q0, … plast, qlast
Run Code Online (Sandbox Code Playgroud)
与另外一个骑手,如果说列表长度不同,那么next(it)当较短的列表用完时,应该返回较长列表中的元素.
尝试解决方案
import itertools
l1=[1,2,3,4,5,6]
l2=['a','b','c','d']
l=[]
for x,y in itertools.zip_longest(l1,l2):
l.extend([x,y])
it=iter(x for x in l if x is not None)
Run Code Online (Sandbox Code Playgroud)
哪种解决了我的问题
print(list(it))
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 6]
Run Code Online (Sandbox Code Playgroud)
有更简单或更好的方法吗?我在SO上搜索了一个解决方案而无法获得解决方案.
您可以使用itertools.chain.from_iterable()展平序列,并使用生成器表达式过滤掉None值:
from itertools import chain, zip_longest
it = (v for v in chain.from_iterable(zip_longest(l1, l2)) if v is not None)
Run Code Online (Sandbox Code Playgroud)
None您可能希望使用专用的标记,而不是用作标记值,以便None在输入列表中使用:
_sentinel = object()
flattened = chain.from_iterable(zip_longest(l1, l2, fillvalue=_sentinel))
it = (v for v in flattened if v is not _sentinel)
Run Code Online (Sandbox Code Playgroud)
如果您想过滤掉虚假值,那么您还可以使用filter(None, ...):
it = filter(None, chain.from_iterable(zip_longest(l1, l2)))
Run Code Online (Sandbox Code Playgroud)
演示:
>>> from itertools import chain, zip_longest
>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = ['a', 'b', 'c', 'd']
>>> it = (v for v in chain.from_iterable(zip_longest(l1, l2)) if v is not None)
>>> list(it)
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 6]
Run Code Online (Sandbox Code Playgroud)
和当地的哨兵:
>>> l1 = [1, None, 2, None, 3, None]
>>> l2 = ['a', 'b', 'c', 'd']
>>> _sentinel = object()
>>> flattened = chain.from_iterable(zip_longest(l1, l2, fillvalue=_sentinel))
>>> it = (v for v in flattened if v is not _sentinel)
>>> list(it)
[1, 'a', None, 'b', 2, 'c', None, 'd', 3, None]
Run Code Online (Sandbox Code Playgroud)
该itertools食谱部分还具有:
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |