Home > Mobile >  How to reduce these code? for every length I'm using a if statement?
How to reduce these code? for every length I'm using a if statement?

Time:09-28

My code

cummulative_num = [['1', '4', '5', '7'], ['2', '5', '6', '9']]

if len(cumulative_num)==1:
    print(*cumulative_num[0])
out=""
if len(cumulative_num)==2:
    for i in cumulative_num[0]:
        for j in cumulative_num[1]:
            out = i j  " "
print(out)
out=""
if len(cumulative_num)==3:
    for i in cumulative_num[0]:
        for j in cumulative_num[1]:
            for k in cumulative_num[2]:
                out = i j k  " "
print(out)


output : 12 15 16 19 42 45 46 49 52 55 56 59 72 75 76 79

Here the output order should be each first array element is added to every element in the second array

Please provide me a Better approach when the array in cummulative_num increases.

CodePudding user response:

Something like this could work:

The * unpacks the lists into product, no matter how many sublists you may have.

from itertools import product
cummulative_num = [['1', '4', '5', '7'], ['2', '5', '6', '9']]
' '.join([''.join(x) for x in product(*cummulative_num)])

Output

'12 15 16 19 42 45 46 49 52 55 56 59 72 75 76 79'

CodePudding user response:

This code is nothing fancy, but it works well and can be adapted well depending on if you want the data stored.

output = [] #Optional
for i in cummulative_num[0]:
    for j in cummulative_num[1]:
        output.append(f'{i}{j}') #Optional
        print(f'{i}{j}')
  • Related