5

假设我有 4 个单词,作为一个字符串。我如何像这样加入他们?

s = orange apple grapes pear

结果将是一个字符串:

"orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear"

我在想:

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

然后使用枚举?那是你用来做这个功能的吗?

4

5 回答 5

4

也许这就是你想要的?

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

如果在 'ab c' 上运行(为了清楚起见),结果是:

bc/ac/ab/abc

(在海报评论后更新。)

于 2010-02-19T21:28:50.853 回答
4
>>> 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'
于 2010-02-19T22:19:45.423 回答
1
>>> 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'
于 2010-02-19T21:56:46.327 回答
1
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)

这给出了单词列表的所有子集,除了空单词、单个单词和所有单词。例如:orangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear

于 2010-02-19T21:30:37.160 回答
1
>>> 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'
于 2010-02-19T22:13:21.723 回答