[英]Permutations and removing tuples
這是我的代碼:
import itertools
def permutations(string):
if len(string) <= 1:
return string
return itertools.permutations(string)
如果輸入'ab'
,則返回[('a', 'b'), ('b', 'a')]
有什么方法可以組合元組項,然后將元組更改為列表項,使其返回: ['ab', 'ba']
嗎?
字符串被視為可迭代,並由itertools.permutations
組合成元組。
要將它們轉換為字符串,只需在元組上使用str.join
(將在更長的排列上起作用):
["".join(x) for x in [('a', 'b'), ('b', 'a')]]
在您的情況下:
["".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.