[英]Permutations and removing tuples
Here's my code: 这是我的代码:
import itertools
def permutations(string):
if len(string) <= 1:
return string
return itertools.permutations(string)
If 'ab'
is input, it returns [('a', 'b'), ('b', 'a')]
如果输入
'ab'
,则返回[('a', 'b'), ('b', 'a')]
Is there any way I can combine the tuple items and then change the tuple into a list item such that it returns: ['ab', 'ba']
? 有什么方法可以组合元组项,然后将元组更改为列表项,使其返回:
['ab', 'ba']
吗?
strings are seen as iterables, and combined into tuples by itertools.permutations
. 字符串被视为可迭代,并由
itertools.permutations
组合成元组。
To convert them back as strings, just use str.join
on the tuples (would work on a longer permutation): 要将它们转换为字符串,只需在元组上使用
str.join
(将在更长的排列上起作用):
["".join(x) for x in [('a', 'b'), ('b', 'a')]]
in your case: 在您的情况下:
["".join(x) for x in itertools.permutations(string)]
[a+b for a,b in itertools.permutations(string)]
与map
:
map(lambda(x):''.join(x), itertools.permutations(string))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.