循环方法在python中混合两个列表

时间:2014-01-11 13:01:37

标签: python python-2.7

如果输入

round_robin(range(5), "hello")

我需要o / p作为

[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']

我试过

def round_robin(*seqs):
list1=[]
length=len(seqs)
list1= cycle(iter(items).__name__ for items in seqs)
while length:
    try:
        for x in list1:
            yield x
    except StopIteration:
        length -= 1

pass

但它会出错

AttributeError: 'listiterator' object has no attribute '__name__'

如何修改代码以获得所需的o / p

7 个答案:

答案 0 :(得分:5)

您可以使用zip功能,然后使用列表理解将结果展平,就像这样

def round_robin(first, second):
    return[item for items in zip(first, second) for item in items]
print round_robin(range(5), "hello")

<强>输出

[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']

zip函数对两个迭代中的值进行分组,如此

print zip(range(5), "hello") # [(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]

我们采用每个元组并用列表理解将其弄平。

但正如@Ashwini Chaudhary建议的那样,请使用roundrobin receipe from the docs

from itertools import cycle
from itertools import islice
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))

print list(roundrobin(range(5), "hello"))

答案 1 :(得分:4)

您可以在此处找到一系列迭代配方:http://docs.python.org/2.7/library/itertools.html#recipes

from itertools import islice, cycle


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))


print list(roundrobin(range(5), "hello"))

编辑:Python 3

https://docs.python.org/3/library/itertools.html#itertools-recipes

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:
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))

print list(roundrobin(range(5), "hello"))

答案 2 :(得分:2)

您可以利用itertools.chain利用itertools.izip(打开元组)(转换元素以创建交错模式)来创建结果

>>> from itertools import izip, chain
>>> list(chain.from_iterable(izip(range(5), "hello")))
[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']

如果字符串长度不等,请使用带填充值的izip_longest(最好是空字符串)

答案 3 :(得分:1)

列表(roundrobin(&#39; ABC&#39;,&#39; D&#39;,&#39; EF&#39;))

输出: [&#39; A&#39;,&#39; D&#39;,&#39; E&#39;,&#39; B&#39;,& #39; F&#39;,&#39; C&#39;]

def roundrobin(*iterables):
    sentinel = object()
    from itertools import chain
    try:
        from itertools import izip_longest as zip_longest
    except:
        from itertools import zip_longest 
    return (x for x in chain(*zip_longest(fillvalue=sentinel, *iterables)) if x is not sentinel)  

答案 4 :(得分:1)

对于任何寻找Python 3的人,请使用此

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))

不同之处在于Python 3的迭代器有__next__()而不是next()https://docs.python.org/3/library/itertools.html#recipes

答案 5 :(得分:0)

Python 2Python 3的两个itertools roundrobin配方的混合看起来像这样:

from itertools import islice, cycle

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    try:
        iter([]).__next__  # test attribute
        nexts = cycle(iter(it).__next__ for it in iterables)
    except AttributeError:  # Python 2 behavior
        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))

print(list(roundrobin(range(5), "hello")))

答案 6 :(得分:-2)

从itertools导入周期开始

A = [[1,2,3],[4,5,6],[7]]

B = [[8],[9,10,11],[12,13]]

对于A中的p:

max1 = len(p) if  max1 <len(p) else max1

对于B中的p:

max1 = len(p) if  max1 <len(p) else max1

i = len(A)

j = 0

C = []

list_num = cycle(k代表范围(i)中的k)

对于list_num中的x:

j += 1

if j == i*3:

    break


if A[x]:

    C.append(A[x].pop(0))

if B[x]:

    C.append(B[x].pop(0)) 

输出=====> [1、8、4、9、7、12、2、5、10、13、3、6、11]