使用itertools生成不重复项目的列表循环列表

问题描述 投票:0回答:1

如果目标是通过组合实现

f"{x1}-{x2}"
对,其中
x1 != x2
,我可以这样做:

import itertools

>>> X = ['1','2','3','4']
>>> [f"-".join(xx) for xx in itertools.combinations(X, 2)]
['1-2', '1-3', '1-4', '2-3', '2-4', '3-4']

但是如果我想以某种循环方式实现所需的输出:

[['2-1', '3-1', '4-1'], ['1-2', '3-2', '4-2'], ['1-3', '2-3', '4-3'], ['1-4', '2-4', '3-4']]

我本可以这样做:

[[f"{x1}-{x2}" for x1 in X if x1 != x2] for x2 in X]

但是 itertools 中是否有一些组合函数的循环可以返回所需输出中所示的二维列表?

有一个指向 roundrobin 的指针 https://docs.python.org/3/library/itertools.html


def roundrobin(*iterables):
    "Visit input iterables in a cycle until each is exhausted."
    # roundrobin('ABC', 'D', 'EF') → A D E B F C
    # Algorithm credited to George Sakkis
    iterators = map(iter, iterables)
    for num_active in range(len(iterables), 0, -1):
        iterators = cycle(islice(iterators, num_active))
        yield from map(next, iterators)

但是有没有更好的方法来达到期望的输出呢?或者嵌套循环是避免对角线的最具可读性和最佳解决方案?

python python-itertools round-robin
1个回答
0
投票

不好,但是使用itertools:

from itertools import *

X = ['1','2','3','4']
expect = [[f"{x1}-{x2}" for x1 in X if x1 != x2] for x2 in X]

result = [*map(list, batched(starmap('{1}-{0}'.format, permutations(X, 2)), len(X)-1))]

print(result == expect)

在线尝试!

© www.soinside.com 2019 - 2024. All rights reserved.