首页 > 解决方案 > 从列表中创建具有多个变体的所有可能组合

问题描述

好的,所以问题如下:

假设我有一个这样的列表[12R,102A,102L,250L],我想要的是所有可能组合的列表,但是只有一个组合/数字。所以对于上面的例子,我想要的输出是:

[12R,102A,250L]
[12R,102L,250L]

我的实际问题要复杂得多,还有更多站点。谢谢你的帮助

编辑:在阅读了一些评论后,我想这有点不清楚。我在这里有 3 个唯一数字,[12、102 和 250],对于某些数字,我有不同的变体,例如 [102A、102L]。我需要的是一种方法来组合不同的位置[12,102,250] 和所有可能的变化。就像我在上面介绍的列表一样。它们是唯一有效的解决方案。[12R] 不是。[12R,102A,102L,250L] 也不是。到目前为止,我已经用嵌套循环做到了这一点,但是这些数字中有很多变化,所以我不能再这样做了

生病再次编辑:好的,所以似乎仍然存在一些混乱,所以我可能会扩展我之前提出的观点。我正在处理的是DNA。12R 表示序列中的第 12 位变为 R。因此溶液 [12R,102A,250L] 表示第 12 位的氨基酸为 R,102 为 A,250 为 L。

这就是为什么像 [102L, 102R, 250L] 这样的溶液不可用的原因,因为相同的位置不能被 2 个不同的氨基酸占据。

谢谢你

标签: python

解决方案


我相信这就是你要找的!

这通过

  • 生成每个前缀可以具有的所有后缀的集合
  • 查找位置总数(将每个子列表的长度相乘)
  • 通过基于集合中成员后缀位置和绝对结果索引(最终结果中的已知位置)的读取索引来旋转每个后缀
import collections
import functools
import operator
import re

# initial input
starting_values = ["12R","102A","102L","250L"]

d = collections.defaultdict(list)  # use a set if duplicates are possible
for value in starting_values:
    numeric, postfix = re.match(r"(\d+)(.*)", value).groups()
    d[numeric].append(postfix)  # .* matches ""; consider (postfix or "_") to give value a size

# d is now a dictionary of lists where each key is the prefix
# and each value is a list of possible postfixes


# each set of postfixes multiplies the total combinations by its length
total_combinations = functools.reduce(
    operator.mul,
    (len(sublist) for sublist in d.values())
)

results = collections.defaultdict(list)
for results_pos in range(total_combinations):
    for index, (prefix, postfix_set) in enumerate(d.items()):
        results[results_pos].append(
            "{}{}".format(  # recombine the values
                prefix,     # numeric prefix
                postfix_set[(results_pos + index) % len(postfix_set)]
            ))

# results is now a dictionary mapping { result index: unique list }

显示

# set width of column by longest prefix string
# need a collection for intermediate cols, but beyond scope of Q
col_width = max(len(str(k)) for k in results)
for k, v in results.items():
    print("{:<{w}}: {}".format(k, v, w=col_width))


0: ['12R', '102L', '250L']
1: ['12R', '102A', '250L']

具有更高级的输入

["12R","102A","102L","250L","1234","1234A","1234C"]

0: ['12R', '102L', '250L', '1234']
1: ['12R', '102A', '250L', '1234A']
2: ['12R', '102L', '250L', '1234C']
3: ['12R', '102A', '250L', '1234']
4: ['12R', '102L', '250L', '1234A']
5: ['12R', '102A', '250L', '1234C']

您可以确认这些值确实是唯一的set

final = set(",".join(x) for x in results.values())
for f in final:
    print(f)

12R,102L,250L,1234
12R,102A,250L,1234A
12R,102L,250L,1234C
12R,102A,250L,1234
12R,102L,250L,1234A
12R,102A,250L,1234C

笔记


推荐阅读