假设我有一个清单:
x = ['abc', 'd', 'efgh']
我正在尝试创建一个函数,以便返回所需的输出:
a d e b f c g h
这主要是取每个元素的第一个字符,然后如果该区域中没有索引则跳到下一个元素。
有没有其他方法可以使用itertools或zip函数进行此操作?
我尝试过:
for i in x:
print(i[0], i[1], i[2]....etc)
但是这只会给我一个错误,因为列表的第二个元素超出了范围。
谢谢!
答案 0 :(得分:2)
当然......仔细看看,试着了解这里发生了什么......
out = []
biggest = max(len(item) for item in x)
for i in range(biggest):
for item in x:
if len(item) > i:
out.append(item[i])
而不是out
,我会考虑yield
来返回生成器中的项目。
答案 1 :(得分:0)
使用itertools的roundrobin
recipe:
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
<强>演示:强>
>>> x = ['abc', 'd', 'efgh']
>>> from itertools import cycle, islice
>>> list(roundrobin(*x))
['a', 'd', 'e', 'b', 'f', 'c', 'g', 'h']
另一种选择是使用itertools.izip_longest
和itertools.chain.from_iterable
:
>>> from itertools import izip_longest, chain
>>> x = ['abc', 'd', 'efgh']
>>> sentinel = object()
>>> [y for y in chain.from_iterable(izip_longest(*x, fillvalue=sentinel))
if y is not sentinel]
['a', 'd', 'e', 'b', 'f', 'c', 'g', 'h']