簡體   English   中英

如何在python中獲取單詞列表的組合

[英]How do I get combinations of a list of words in python

我正在嘗試制作一個腳本,如果我給它一個單詞列表,例如 ('1', '2', '3') 它會給我:

1 12 13 123 232 2 21 23 213 231 3 31 32 31 32 312 321

我已經嘗試過 itertools 但我無法弄清楚我該怎么做?

謝謝

您需要使用排列而不是組合的itertoolspowerset 配方的變體:

from itertools import permutations, chain

def powerperm(iterable):
    s = list(iterable)
    return chain.from_iterable(permutations(s, r) for r in range(1, len(s)+1))

inp = ('1', '2', '3')

out = list(map(''.join, powerperm(inp)))
out

輸出: ['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']

暫無
暫無

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

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