How to process multiple Python factors.

Asked 2 years ago, Updated 2 years ago, 17 views

This is how the list is saved. all_list=[['frodo', 'fradi'], ['abc123']]

I want to calculate using the productCotton Hand over product (all_list[0], all_list[1]).

However, if the all_list is variable, product(all_list[0],all_list[1],...,all_list[n]) I want to hand over the factor like this.

What should I do?

python

2022-09-20 19:08

2 Answers

def doSomething(*args):
    for i in range(len(args)):
        print(args[i])

doSomething(1)
doSomething(1,2)
doSomething(1,2,3)
doSomething(1,2,3,4)
doSomething(1,2,3,4,5)

list_of_lists = [ [1,2,3], [4,5,], [6] ]

I watched it several times. You want to use the code like product(all_list[0], all_list[1], ..., all_list[n]), right? But you can't write the code like that. I can't write it like that. You could write it, but you really have to force yourself to write it. And there's a reason why everything can't be done. This is Anti Pattern.

Don't write it like that. Just

Make it work as product(all_list) like someone else's answer.


2022-09-20 19:08

After handing over the all_list itself to the function, look at the length of the all_list inside the function and handle it accordingly.

Please refer to the code below.

list1=[['frodo', 'fradi'], ['abc123']]
list2=[['aaa'],['bbb'],['ccc']]
list3=[]

def product(lists):
    if len(lists)==2:
        print ('What to do when there are 2 arguments')
    elif len(lists)>2:
        print ('What to do when there are more than 3 arguments')

product(list1)
product(list2)
product(list3)
product(list1)


2022-09-20 19:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.