如何以Pythonic方式将多个列表分组到单个列表中?

2024-10-02 00:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从列表列表返回列表的函数,其中返回列表按索引号对每个列表的成员进行分组。代码和示例:

def listjoinervar(*lists: list) -> list:
    """returns list of grouped values from each list 
        keyword arguments:
        lists: list of input lists
    """ 
    assert(len(lists) > 0) and (all(len(i) == len(lists[0]) for i in lists))
    joinedlist = [None] * len(lists) * len(lists[0])
    for i in range(0, len(joinedlist), len(lists)):
        for j in range(0, len(lists[0])):
            joinedlist[i//len(lists[0]) + j*len(lists[0])] = lists[i//len(lists[0])][j]
    return joinedlist

a = ['a', 'b', 'c']
b = [1, 2, 3]
c = [True, False, False]
listjoinervar(a, b, c)
# ['a', 1, True, 'b', 2, False, 'c', 3, False]

有没有办法使用itertools、生成器等让它更具Pythonic?我已经看过类似this的例子,但是在我的代码中没有与单个列表的元素进行交互。谢谢


Tags: of函数代码infalsetrue列表for
3条回答

使用zip和列表理解:

from typing import List, Any

def listjoinervar(*args: List[Any]) -> List[Any]:
    return [item for sublist in list(zip(*args)) for item in sublist]

用法:

>>> a = ["a", "b", "c"]
>>> b = [1, 2, 3]
>>> c = [True, False, False]
>>> listjoinervar(a,b,c)
['a', 1, True, 'b', 2, False, 'c', 3, False]

类型注释的使用是可选的。你知道吗

在正常情况下,我也会使用itertools.chain,就像奥斯汀的回答一样。你知道吗

但是,为了完整起见,一个不导入任何内容的替代解决方案:

def join_lists(*a):
    return [element for sub in zip(*a) for element in sub]

a = ['a', 'b', 'c']
b = [1, 2, 3]
c = [True, False, False]

join_lists(a, b, c)

输出:

['a', 1, True, 'b', 2, False, 'c', 3, False]

使用^{}+^{}

from itertools import chain

def listjoinervar(*a):
    return list(chain.from_iterable(zip(*a)))

用法:

>>> a = ['a', 'b', 'c']
>>> b = [1, 2, 3]
>>> c = [True, False, False]
>>> listjoinervar(a, b, c)
['a', 1, True, 'b', 2, False, 'c', 3, False]

相关问题 更多 >

    热门问题