【问题标题】:Generate all combinations of words from nested list of letters [duplicate]从嵌套的字母列表中生成所有单词组合[重复]
【发布时间】:2020-07-01 18:01:37
【问题描述】:

问题是按字典顺序生成单词。所以从Letters生成Allword

#we have a list containing lists which contains alphabets
#for eg.:
Letters=[['A','B','C'],['D','E','F'],['P','Q','R','S']]
#This is input and output is supposed to be like this
Allword=['ADP', 'ADQ', 'ADR', 'ADS', 'AEP', 'AEQ', 'AER', 'AES', 'AFP', 'AFQ', 'AFR', 'AFS', 'BDP', 'BDQ', 'BDR', 'BDS', 'BEP', 'BEQ', 'BER', 'BES', 'BFP', 'BFQ', 'BFR', 'BFS', 'CDP', 'CDQ', 'CDR', 'CDS', 'CEP', 'CEQ', 'CER', 'CES', 'CFP', 'CFQ', 'CFR', 'CFS']

我使用了迭代算法,它只在 List Letters 的长度为 3 时才有用

    for i in Letters[0]:
        for j in Letters[1]:
            for k in Letters[2]:
                    b=i+j+k
                    Allword.append(b)

我正在尝试找到一种可以完成相同工作但不受长度限制的算法。我该怎么办?

【问题讨论】:

    标签: python list algorithm traversal


    【解决方案1】:

    您需要内部列表的笛卡尔积。你有itertools.product。然后只需将生成的元组映射到 str.join 以获取字符串列表:

    from itertools import product
    
    list(map(''.join, product(*Letters)))
    # ['ADP', 'ADQ', 'ADR', 'ADS', 'AEP', 'AEQ'...
    

    【讨论】:

      猜你喜欢
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      相关资源
      最近更新 更多