【问题标题】:Python- How to find all possible combinations in an array of stringPython-如何在字符串数组中找到所有可能的组合
【发布时间】:2020-07-01 18:41:38
【问题描述】:

我有一个字符串数组,例如 ['abc', 'xy','d', 'mzqr']

如果有一个简单的解决方案可以找到所有可能的字符组合,例如:

  • axdm
  • 艾德姆
  • 艾兹
  • 一个...
  • bxdm
  • ...

谢谢!

【问题讨论】:

标签: arrays python-3.x iterator


【解决方案1】:

使用itertools.product:

from itertools import product

lst = ['abc', 'xy','d', 'mzqr']

list(map(''.join, product(*lst)))
# ['axdm', 'axdz', 'axdq', 'axdr', 'aydm', 'aydz', 'aydq', 'aydr', 
#  'bxdm', 'bxdz', 'bxdq', 'bxdr', 'bydm', 'bydz', 'bydq', 'bydr', 
#  'cxdm', 'cxdz', 'cxdq', 'cxdr', 'cydm', 'cydz', 'cydq', 'cydr']

product 接受任意数量的可迭代对象(这里是您的 *-unpacked 字符串列表)并以 tuples 上的惰性迭代器的形式生成它们的笛卡尔积。这使用str.join 将元组转回字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-06
    • 2015-03-09
    • 2017-11-11
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多