簡體   English   中英

如何從字符串列表中創建特定長度的所有可能訂單

[英]how to create all possible orders in a specific length from a list of strings

我有一個需要容納 6 個字符的字符串列表。 字符串可以拆分,但字符串中的字符不能隨機化。 字符串具有不同的長度(4 個和 3 個字符)

我用 itertools 嘗試了一些東西,並且知道如何獲得所有可能性,但不知道如何僅獲得具有特定長度要求的可能性。

可以從列表條目中省略第一個零。

列表示例:

wordlist = ["0254", "0294", "0284", "0289", "027", "024", "026", "088"]

可以得到025427254027270254027254 (列表的 0 和 4 )和明顯的027088088027 (列表的 4 和 7 )甚至272488 (列表的 4 、 5 和 7 )這樣的組合

我認為解決方案在於 itertools 與其他東西的結合。

只需使用標准雙循環並檢查您是否需要/可以刪除零以獲得所需的長度

combinations = []
for i in wordlist:
    for j in wordlist:
        if len(i) == 4 and len(j) == 4:  # remove both zeros
            combinations.append(i[1:] + j[1:]) 
        elif len(i) == 3 and len(j) == 3:
            combinations.append(i + j)  # dont remove any zero
        else:
            combinations.append(i[1:] + j)  # remove first element zero
            combinations.append(i + j[1:])  # remove second element zero

這將為您提供所有可能的組合(包括與自身匹配的元素)

暫無
暫無

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

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