1

I have the following list:

listEx = ['123','456','342','432']

How can I take the different compilations of numbers that can be made? For example for the first item of the list 123 the compilation should be:[1,2,3],[1,23],[12,3],[123]

The first compliation can be done by using the following:

[int(listEx[0][0]),int(listEx[0][1]),int(listEx[0][2])]
[int(listEx[0][0]),int(listEx[0][1:])]
                  .
                  .
                  .

Is there a more elegant and dynamic way of doing it ? More speciffically how can i create the following:

[[[1,2,3],[4,5,6],[3,4,2],[4,3,2]],
  [[1,23],[4,56],[3,42],[4,32]],
             .
             .
 ]
Mpizos Dimitris
  • 4,819
  • 12
  • 58
  • 100

2 Answers2

2

You can use a list comprehension to loop over your list can use indexing to split the strings and insert the comma into your string then add the slices. And for inserting two comma you can use str.join() method:

>>> [[','.join(i)]+[str(i[:x]+','+i[x:]).strip(',') for x in range(3)] for i in listEx]
[['1,2,3', '123', '1,23', '12,3'], ['4,5,6', '456', '4,56', '45,6'], ['3,4,2', '342', '3,42', '34,2'], ['4,3,2', '432', '4,32', '43,2']]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

Try this if you want the output in the order you specified.

listEx = ['123','456','342','432']
combinations = list()
for i in listEx:
    itr_list = list()
    itr_list.append(','.join(i))
    for x in range(1,len(i)):
            itr_list.append(','.join([i[:x],i[x:]]))
    itr_list.append(i)
    combinations.append(itr_list)
output = list()
for i in range(len(combinations)):
    itr_list = list()
    for j in range(len(combinations[i])):
        itr_list.append(combinations[j][i])
    output.append([itr_list])
print output
Ravi
  • 36
  • 3