簡體   English   中英

從python中未知數量的列表中創建所有可能的字符組合

[英]Create all possible char combinations from an unknown amount of lists in python

我想從列表中創建所有可能的字符組合。 第一個字符需要來自第一個數組,第二個字符來自第二個數組,依此類推。

如果我有以下列表:

char1 = ['a','b','c']
char2 = ['1','2']

可能的字符串是:a1、a2、b1、b2、c1 和 c2。 我如何使代碼從未知數量的未知大小的列表中生成所有組合?

問題是我不知道會有多少個列表。 在代碼運行時,列表的數量將由用戶決定。

這是itertools.product()的任務! 查看文檔: https : //docs.python.org/2/library/itertools.html#itertools.product

>>> ["%s%s" % (c1,c2) for (c1,c2) in itertools.product(char1, char2)]
['a1', 'a2', 'b1', 'b2', 'c1', 'c2']

是的,它擴展到可變數量的未知大小的列表。

如上所述,您可以使用itertools.product()

由於您不知道列表的數量,您可以將列表列表作為參數傳遞:

import itertools

lists = [
    ['a','b','c'],
    ['1','2']
]

["".join(x) for x in itertools.product(*lists)]

結果:

['a1', 'a2', 'b1', 'b2', 'c1', 'c2']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM