Sriker Ch
Sriker Ch

Reputation: 133

possible combinations of strings in an array in python?

arr=['one','two','three']

Result must be like this: onetwo,twothree,onethree

itertools.permutations will not work in this situation.

we can do this by simply adding for loops and appending them ,that works for small arrays but takes time for big arrays.
I was wondering is there any way (like itertools.permutations)this can be achieved?

Upvotes: 2

Views: 1158

Answers (2)

galaxyan
galaxyan

Reputation: 6151

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'])

Upvotes: 1

wim
wim

Reputation: 363586

Perhaps what you wanted was the itertools.combinations?

>>> [''.join(comb) for comb in (itertools.combinations(arr, 2))]
['onetwo', 'onethree', 'twothree']

Upvotes: 4

Related Questions