0

I have a string array such as ['abc', 'xy','d', 'mzqr']

I wounder if there is a simple solution to find all possible characters combination like:

  • axdm
  • aydm
  • aydz
  • a...
  • bxdm
  • ...

Thanks !

  • 1
    Does this answer your question? [What is the best way to generate all possible three letter strings?](https://stackoverflow.com/questions/7074051/what-is-the-best-way-to-generate-all-possible-three-letter-strings) – DYZ Mar 20 '20 at 15:50

1 Answers1

0

Use 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 takes any number of iterables (here your *-unpacked list of strings) and produces their cartesian product in the form of a lazy iterator over tuples. This the uses str.join to turn the tuples back into strings.

user2390182
  • 72,016
  • 6
  • 67
  • 89