如何通过每个位置的可能性列表获取每个字符串变化

假设我有一个名为 的列表列表master_list,它具有以下属性:

  1. 中的每个列表都master_list包含单个数字正整数的字符串

  2. 中的每个列表master_list的长度从 2 到 5

  3. master_list长度从 1 到 8

我想要做的是使用每个位置的可能性列表返回一个字符串变体列表。

这是 a 的示例master_list以及输出的样子:

master_list = [['3', '2', '6'], ['6', '5', '3', '9'], ['9', '8', '6']]


#  In this case the output would contain 3*4*3 = 36 elements 


output = ["339","366","399","658","636","258","268","669","668","266","369","398",

           "256","296","259","368","638","396","238","356","659","639","666","359",

           "336","299","338","696","269","358","656","698","699","298","236","239"]


慕尼黑5688855
浏览 84回答 1
1回答

潇潇雨雨

'已经尝试使用嵌套的 for 循环遍历每个列表,然后我意识到我需要使用递归,因为列表的数量是可变的。但我坚持如何做到这一点。嵌套循环让我得到了上面的输出,但它本质上是硬编码的。试试这个(它使用itertools.product):import itertoolsli = [['3', '2', '6'], ['6', '5', '3', '9'], ['9', '8', '6']]result = [''.join(i) for i in itertools.product(*li)]print(result)输出:['369', '368', '366', '359', '358', '356', '339', '338', '336', '399', '398', '396', '269', '268', '266', '259', '258', '256', '239', '238', '236', '299', '298', '296', '669', '668', '666', '659', '658', '656', '639', '638', '636', '699', '698', '696']如果要将每个元素转换为int:result = [int(''.join(i)) for i in itertools.product(*li)]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python