简体   繁体   English

使用Python查找所有不同的组合

[英]Find all different combinations with Python

I want to create a function in python that as input takes a list with an unspecified amount of strings whose length is also not standard or the same with each other. 我想在python中创建一个函数,作为输入,它使用一个列表,其中包含未指定数量的字符串,这些字符串的长度也不是标准的或彼此相同。 The input would be like this: 输入如下所示:

list = ['1234', '4', '97', ... , '542']

The first element of this list represents all the possible numbers that could be the first digit of a number, the second element the possible numbers that could be the second digit and so on. 此列表的第一个元素表示可能是数字的第一位的所有可能数字,第二个元素表示可能是第二位的可能的数字,依此类推。 As output, I want to have a list with all the possible numbers that could be generated this way. 作为输出,我希望有一个列表,其中包含所有可以通过这种方式生成的数字。 Here is an example: 这是一个例子:

input = ['12', '45', '865']
output = ['148', '146', '145', '158', '156', '155',
 '248', '246', '245', '258', '256', '255']

Is there an algorithm for this? 是否有针对此的算法? I am not completely new to python but this problem has me at a loss. 我对python并不完全陌生,但是这个问题令我无所适从。 Thanks for any help. 谢谢你的帮助。

from itertools import product

input = ['12', '45', '865']

[''.join(prod) for prod in product(*input)]

# ['148', '146', '145', '158', '156', '155', '248', '246',
#  '245', '258', '256', '255']

itertools.product takes a number of iterables as parameters, and yields their cartesian product. itertools.product将许多iterables作为参数,并产生其笛卡尔积。
As your iterables (your strings) are in a list, we use the *input syntax to unpack the elements of the list to separate positional parameters. 由于您的可迭代项(您的字符串)在列表中,因此我们使用* input语法将列表中的元素解包以分隔位置参数。

Tested with Python 2.7 经过Python 2.7测试

Input = ['12', '45', '865']
out = [[]]

# algo
for liste in Input:
    out = [x + [y] for x in out for y in liste]
    #print out # un comment to see how algo works

index = 0
while index < len(out):
    out[index] = ''.join(out[index])
    index += 1

print out

# prodcues:
# ['148', '146', '145', '158', '156', '155',
#  '248', '246', '245', '258', '256', '255']
# The while loop can be reduced to:
# print [''.join(liste) for liste in out]

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

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