如何生成字符之间带空格的字符串的所有可能组合?Python

前端之家收集整理的这篇文章主要介绍了如何生成字符之间带空格的字符串的所有可能组合?Python前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何生成字符之间带空格的字符串的所有可能组合?
[in]: "foobar"

[out]: 
['foobar','f oobar','fo obar','f o obar','foo bar','f oo bar','fo o bar','f o o bar','foob ar','f oob ar','fo ob ar','f o ob ar','foo b ar','f oo b ar','fo o b ar','f o o b ar','fooba r','f ooba r','fo oba r','f o oba r','foo ba r','f oo ba r','fo o ba r','f o o ba r','foob a r','f oob a r','fo ob a r','f o ob a r','foo b a r','f oo b a r','fo o b a r','f o o b a r','foobar','f o o b a r']

解决方法

import itertools as it

def func(s):
   if not s:
       return [s]
   binary = it.product(['',' '],repeat=len(s)-1)
   zipped = (it.izip_longest(s,comb,fillvalue='') for comb in binary)
   return [''.join(it.chain.from_iterable(x)) for x in zipped]

func('foobar')

输出

['foobar','f o o b a r']

猜你在找的Python相关文章