python - 如何获取每个字符串变体以及每个位置的可能性列表

标签 python string list

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

  1. master_list 中的每个列表都包含单位正整数的字符串
  2. master_list 中的每个列表的长度为 2 到 5
  3. master_list 的长度为 1 到 8

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

以下是 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"]

最佳答案

've tried iterating through each list with nested for loops, then I realized that I would need to use recursion because the number of lists is variable. But I'm stuck on how to do that. The nested loops got me the output above but its essentially hard coded for that case.

试试这个(它使用 itertools.product ):

import itertools

li = [['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)]

关于python - 如何获取每个字符串变体以及每个位置的可能性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60088165/

相关文章:

php - Python 相当于 php 包

python - 无法挤压 dim[1],期望维度为 1,得到 499

java - 优化字符串操作代码

python - 如何在2 2d列表中将第二列添加在一起?

c# - 在 F# 中使用 SqlDataReader

python - 如何使用 `urlparse` 检查 URL 是否有效?

python - 如何对字符串数组执行 bincount?

c# - 如何在 C# 中返回空值而不是空值

android - 实时编辑用户输入

列表项的python连接组合