开发者

Combining words in Python (permutations?)

Suppose I have 4 words, as a string. How do I join them all like this?

s = orange apple grapes pear

The result would be a String:

开发者_StackOverflow"orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear"

I am thinking:

list_words = s.split(' ')
for l in list_words:

And then use enumerate? Is that what you would use to do this function?


Maybe this is what you want?

s = "orange apple grapes pear"

from itertools import product
l = s.split()
r='/'.join(''.join(k*v for k,v in zip(l, x))
           for x in product(range(2), repeat=len(l))
           if sum(x) > 1)
print r

If run on 'a b c' (for clarity) the result is:

bc/ac/ab/abc

(Updated after comment from poster.)


>>> from itertools import combinations
>>> s = "orange apple grapes pear".split()
>>> '/'.join([''.join(y) for y in [ x for z in range(len(s)) for x in combinations(s,z)] if len(y)>1])
'orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/orangegrapespear/applegrapespear'


s = 'orange apple grapes pear'

list_words = s.split()

num = len(list_words)
ans = []
for i in xrange(1,2**num-1):
  cur = []
  for j,word in enumerate(list_words):
    if i & (1 << j):
      cur.append(word)
  if len(cur) > 1: 
    ans.append(''.join(cur))
print '/'.join(ans)

This gives all subsets of the list of words except the empty one, single words, and all of them. For your example: orangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear


>>> import itertools
>>> from itertools import combinations
>>> s = "orange apple grapes pear".split()
>>> res=[]
>>> for i in range(2,len(s)+1):
...     res += [''.join(x) for x in combinations(s,i)]
... 
>>> '/'.join(res)
'orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/orangegrapespear/applegrapespear/orangeapplegrapespear'


>>> s = "orange apple grapes pear".split()
>>> '/'.join(''.join(k) for k in [[s[j] for j in range(len(s)) if 1<<j&i] for i in range(1<<len(s))] if len(k)>1)
'orangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear/orangeapplegrapespear'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜