首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >快速压缩列表,同时通过自行车完成较短的列表

快速压缩列表,同时通过自行车完成较短的列表
EN

Stack Overflow用户
提问于 2018-01-19 17:08:21
回答 4查看 237关注 0票数 1

--请注意,这不是 这个职位 的重复,因为我想压缩超过2个列表(或者至少我不能简单地泛化该帖子,以便在这里使用而不需要显式循环)

我希望找到以某种方式合并列表的最佳实现(就速度而言)。输入是一个列表(或多个元组),排序使下一个列表的长度总是上一个列表的倍数。例如:

代码语言:javascript
运行
复制
a = ['A', 'B', 'C', 'D']
b = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
input_list = [a, b]

输出是以下内容的合并列表:

代码语言:javascript
运行
复制
output = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H']

也就是说,较短的列表(在本例中为a)都是通过循环自身来扩展为最长的列表(在本例中为b),这样列表将具有相同的长度。然后,所有列表都以垂直叠加的方式合并。

目前,我有一个实现,主要做以下工作:

代码语言:javascript
运行
复制
step 1            step 2           step 3 
======            ========         ======
ABCD              ABCDABCD
ABCDEFGH -------> ABCDEFGH ------> AABBCCDDAEBFCGDH

它起作用,但没有效率:

代码语言:javascript
运行
复制
def flatten_list(value):
    return sum(value, [])

def group(value):
    for idx in reversed(range(1, len(value))):
        multiplier = int(len(value[idx]) / len(value[idx - 1]))
        if multiplier > 1:
            value[idx - 1] = flatten_list([value[idx - 1] for i in range(multiplier)])
    return flatten_list(list(zip(*value)))

是否有更快的实现?性能对于我的应用程序来说是至关重要的,因为输入可能是巨大的。如有任何建议,敬请谅解!

EN

回答 4

Stack Overflow用户

发布于 2018-01-19 17:41:37

使用cyclechain,来自itertoolsislice

代码语言:javascript
运行
复制
list(chain(*islice(
    zip(*(cycle(l) for l in input_list)), 
    0, len(max(input_list, key=len)))))
# ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H']

或在其各部分:

代码语言:javascript
运行
复制
# generator producing cycles of each list
(cycle(l) for l in input_list)  
# zip these cycles together: ('A', 'A') -> ('B', 'B') -> infinitely
zip(*...)  
# take a slice of this iterable of tuples with the length of the longest list
islice(..., 0, len(max(input_list, key=len)))
# chain those tuples together into one list
list(chain(*...))   

或举例说明:

代码语言:javascript
运行
复制
lists = [
                 #        chain--┐-----┐-----┐
                 #              ┌--┐  ┌--┐  ┌--┐     
                 #        | ┌-┐ | ┌-┐ | ┌-┐ | ┌-┐  | ┌-┐     
   [1],          # cycle: | |1|,| |1|,| |1|,| |1|, | |1|, ...
   [1, 2],       # cycle: | |1|,| |2|,| |1|,| |2|, | |1|, ...
   [1, 2, 3, 4], # cycle: | |1|,| |2|,| |3|,| |4|, | |1|, ...
]                #        | └-┘ | └-┘ | └-┘ | └-┘  | └-┘  
                 #        |  └--┘  └--┘  └--┘      |
                 #        | zip   zip   zip   zip  | zip  ...
                 #        |                        |    
                 #   islice start           islice stop
                 #   -->  [1,1,1,1,2,2,1,1,3,1,2,4]

它的时间复杂性是O(n),其中n是输出列表的长度。在Python2中,您将不得不使用itertools.izip而不是zip,因为后者将尝试构建无限列表。

票数 4
EN

Stack Overflow用户

发布于 2018-01-19 17:50:41

使用迭代工具配方

两个输入

代码语言:javascript
运行
复制
import itertools as it


a = list("ABCD")
b = list("ABCDEFGH")

list(it.chain.from_iterable(roundrobin(zip(it.cycle(a), b))))
# ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H']

itertools.cycle()无限扩展了较短的可迭代性。zip()在较短的可迭代性之后停止迭代。roundrobin处理可迭代性之间的元素交织。

较长的输入

要处理两个以上的输入,我们需要循环除最后一个可迭代之外的所有输入:

代码语言:javascript
运行
复制
def interleave(*inputs):
    *rest, last = inputs
    cycles = (it.cycle(x) for x in rest)
    return list(it.chain.from_iterable(mit.roundrobin(zip(*cycles, last))))

现在,对于两个或多个输入迭代,我们可以应用interleave函数:

代码语言:javascript
运行
复制
p = list("ab")
q = list("abcd")
r = list("abcdef")

input_list_1 = [a, b]
input_list_2 = [p, q, r]


print(interleave(*input_list_1))
# ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'A', 'E', 'B', 'F', 'C', 'G', 'D', 'H']
print(interleave(*input_list_2))
# ['a', 'a', 'a', 'b', 'b', 'b', 'a', 'c', 'c', 'b', 'd', 'd', 'a', 'a', 'e', 'b', 'b', 'f']

注意:您可以从roundrobin重新实现医生们配方,也可以安装第三方库为您实现它,例如more_itertools> pip install more_itertools,然后是Python,from more_itertools import roundrobin

票数 2
EN

Stack Overflow用户

发布于 2018-01-19 17:33:16

itertools.cycle应用于所有短于最长的列表,并将它们全部压缩在一起,使结果变平。

代码语言:javascript
运行
复制
def special_zip(*lsts):
    max_len = max(map(len, lsts))
    cyclic = [lst if len(lst) == max_len else itertools.cycle(lst) for lst in lsts]
    return (el for grp in zip(*cyclic) for el in grp)

这应该是O(2n),其中n是列表长度之和。如果您知道最长的列表,并且可以单独传递它,这将变成O(n)。类似地,如果您知道需要多少输出(因为您只需对每个列表应用itertools.cycle并从无限输出中提取)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48346169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档