2013-10-20 171 views
1

比方说,我有一个列表:如何打印出每个列表的第一个字符,然后打印下一个字符

x = ['abc', 'd', 'efgh'] 

我试图创建一个功能,使得其所需的输出将返回:

a d e b f c g h 

这实质上是采取每个元素的第一个字符,然后跳到下一个元素,如果该区域没有索引。

有没有使用itertools或zip函数做这个W/O的替代方法?

我试着这样做:

for i in x: 
     print(i[0], i[1], i[2]....etc) 

但由于列表的第二个元素超出范围只给我一个错误。

谢谢!

回答

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在发电机回报的项目。

0

使用roundrobin recipe从itertools:

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_longestitertools.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'] 
+0

我会'y不是哨兵'...以防万一'y'有一个时髦的定义'__ne__'。 (当然,这对弦乐无关紧要,但这是一个很好的习惯)。 – mgilson

+0

@mgilson感谢您解决这个问题,实际上在我的真实代码中使用了'not',但是在这里使用了'!=',因为我对此有点怀疑。 ;-) –

+0

考虑你的观众:) – beroe