gpt4 book ai didi

python - 如何从字符串字符构建所有可能的对

转载 作者:行者123 更新时间:2023-12-02 16:10:01 28 4
gpt4 key购买 nike

我想从一个字符串中构建包含字符串字符所有可能组合的对。

# Exemple :
s = "ABCD"

# Desired result :
["A", "BCD"]
["B", "ACD"]
["C", "ABD"]
...
["AB", "CD"]
...
["BC", "AD"]
...
["ABC", "D"]
["ABD", "C"]
["ACD", "B"]
["BCD", "A"]

最佳答案

一种方法是生成索引的组合,而不是随着r的增加生成元素本身:1, 2, .., length - 1。然后我们找到剩余的组合选择后的索引。 itemgetter 可以获取给定索引的值,我们可以将它们作为字符串收集在列表中:

from itertools import combinations
from operator import itemgetter

# given string and range till its length
s = "ABCD"
rng = range(len(s))

result = []
# for each combination possibility r...
for r in range(1, len(s)):
# get the indices from `rng`
for inds in combinations(rng, r):
# find `others` that are not `inds` in `rng`
others = [ind for ind in rng if ind not in inds]

# now index into the string with these indices to find pairs
first = itemgetter(*inds)(s)
second = itemgetter(*others)(s)

# store the stringifed pair
result.append(["".join(first), "".join(second)])

给出

>>> result

[["A", "BCD"],
["B", "ACD"],
["C", "ABD"],
["D", "ABC"],
["AB", "CD"],
["AC", "BD"],
["AD", "BC"],
["BC", "AD"],
["BD", "AC"],
["CD", "AB"],
["ABC", "D"],
["ABD", "C"],
["ACD", "B"],
["BCD", "A"]]

关于python - 如何从字符串字符构建所有可能的对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68260395/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com