简体   繁体   English

如何在python中获取单词列表的组合

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

I am trying to make a script that if I gave it a list of words such as ('1', '2', '3') it would give me:我正在尝试制作一个脚本,如果我给它一个单词列表,例如 ('1', '2', '3') 它会给我:

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

I have tried itertools but I couldn't figure it out How can I do this?我已经尝试过 itertools 但我无法弄清楚我该怎么做?

Thankyou谢谢

You need a variant of the powerset recipe from itertools using permutations instead of combinations:您需要使用排列而不是组合的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

output: ['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']输出: ['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