简体   繁体   English

没有重复的组合(python)

[英]Combinations without repetition (python)

I want to make the following combinations:我想做以下组合:

string.1 string.1
string.2 string.2 string.1
string.3 string.3 string.2 string.1
string.4 string.4 string.3 string.2
string.4 string.1

Each item should be combined with every other one, but the order does not matter, ie string.4 string.1 is the same as string.1 string.4 .每个项目都应该与其他项目组合,但顺序无关紧要,即string.4 string.1string.1 string.4相同。 Also, there should be a maximum of 4 combinations per line.此外,每行最多应有 4 个组合。 Each item in the first column is combined with each one in the other columns.第一列中的每个项目都与其他列中的每个项目组合在一起。 For example in line 2, there are the combinations string.2-string.2 & string.2-string.1 .例如在第 2 行,有string.2-string.2 & string.2-string.1的组合。

This is my code:这是我的代码:

import itertools
BLOCKS=4
DB="string"
getiter = lambda : itertools.chain( range(1, BLOCKS+1))
for i in getiter():
    for j in range(1, BLOCKS, 4):
            emit = f"{DB}.{i}"
            for k in range(4):
                    if j + k > BLOCKS:
                            break
                    emit += " {}.{}".format(DB, j+k)
            print(emit)

And this is my current output:这是我目前的 output:

string.1 string.1 string.2 string.3 string.4
string.2 string.1 string.2 string.3 string.4
string.3 string.1 string.2 string.3 string.4
string.4 string.1 string.2 string.3 string.4

Here, there are combinations that are superfluous.在这里,有些组合是多余的。 How do I get rid of those?我该如何摆脱这些?

Maybe something like that:也许是这样的:

import itertools
BLOCKS=4
DB="string"
getiter = lambda : itertools.chain( range(1, BLOCKS+1))
for i in getiter():
    emit = f"{DB}.{i}"
    for k in range(1, BLOCKS+1):
        if k > BLOCKS: break
        else if k == i: continue #<========== Added
        emit += " {}.{}".format(DB, k)
    print(emit)

(Note that the second loop (j) seems useless so I did remove it) (请注意,第二个循环(j)似乎没用,所以我确实删除了它)

Output: Output:

string.1 string.2 string.3 string.4
string.2 string.1 string.3 string.4
string.3 string.1 string.2 string.4
string.4 string.1 string.2 string.3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM