python 数组中字符串的可能组合?
possible combinations of strings in an array in python?
arr=['one','two','three']
结果一定是这样的:
onetwo,twothree,onethree
itertools.permutations will not work in this situation.
我们可以通过简单地添加 for 循环并附加它们来做到这一点,这适用于小型数组,但对于大型数组则需要时间。
我想知道有什么方法可以实现吗?(like itertools.permutations)
也许您想要的是 itertools.combinations
?
>>> [''.join(comb) for comb in (itertools.combinations(arr, 2))]
['onetwo', 'onethree', 'twothree']
for two lists
- create a list with equal length compare with other list
- zip new list with other list
- put all sublist together
- join list
from itertools import permutations
arr1=['name1','name2']
arr2=['name3','name4']
set( map(lambda x: ''.join(x),reduce( lambda x,y:x+y, [ zip(i,arr1) for i in permutations(arr2,len(arr1)) ] ) ) )
output:
set(['name3name1', 'name3name2', 'name4name1', 'name4name2'])
arr=['one','two','three']
结果一定是这样的:
onetwo,twothree,onethree
itertools.permutations will not work in this situation.
我们可以通过简单地添加 for 循环并附加它们来做到这一点,这适用于小型数组,但对于大型数组则需要时间。
我想知道有什么方法可以实现吗?(like itertools.permutations)
也许您想要的是 itertools.combinations
?
>>> [''.join(comb) for comb in (itertools.combinations(arr, 2))]
['onetwo', 'onethree', 'twothree']
for two lists
- create a list with equal length compare with other list
- zip new list with other list
- put all sublist together
- join list
from itertools import permutations
arr1=['name1','name2']
arr2=['name3','name4']
set( map(lambda x: ''.join(x),reduce( lambda x,y:x+y, [ zip(i,arr1) for i in permutations(arr2,len(arr1)) ] ) ) )
output:
set(['name3name1', 'name3name2', 'name4name1', 'name4name2'])