假设我有4个单词,作为字符串。 我如何加入这些呢?
s = orange apple grapes pear
结果将是一个字符串:
"orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear"
我在想:
list_words = s.split(' ')
for l in list_words:
然后使用枚举?那是你用来做这个功能的吗?
答案 0 :(得分: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
如果在'a b c'上运行(为清楚起见),结果为:
bc/ac/ab/abc
(海报评论后更新。)
答案 1 :(得分: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'
答案 2 :(得分: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
答案 3 :(得分: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'
答案 4 :(得分: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'