简体   繁体   中英

Can someone help me simplify my Python function?

I'm working on my homework assignment in Python. I made a function that uses lists as input but I'm not very good at Python programming yet. The function works the way it's supose to but it's a mess. The only input that's really used is "values". This input is a list containing more lists. Inside the list there has to be atleast 2 lists. The max amount of lists allowed inside the input is 8. If the input only has 2 lists then the other 6 lists have to be [0]. An example for input: [[0, 1],[3, 8, 10]]. With the example input the output has to be:

[0, 3, 0, 0, 0, 0, 0, 0]

[0, 8, 0, 0, 0, 0, 0, 0]

[0, 10, 0, 0, 0, 0, 0, 0]

[1, 3, 0, 0, 0, 0, 0, 0]

[1, 8, 0, 0, 0, 0, 0, 0]

[1, 10, 0, 0, 0, 0, 0, 0]

Ofcourse the lists inside the input can be a lot bigger and there can be more. This is just a small example but I hope you get the idea. Have a look below for the code I made.

def mget(self, values):
    val = [[0], [0], [0], [0], [0], [0], [0], [0]]
    if self._steps[1] is 0:
        print("Error: operation not possible on field \"" + self._name + "\"")
    else:
        for x in range(len(val)):
            try:
                if not values[x]:
                    val[x] = [0]
                else:
                    val[x] = values[x]
            except IndexError:
                val[x] = [0]
        for a in val[0]:
            for b in val[1]:
                for c in val[2]:
                    for d in val[3]:
                        for e in val[4]:
                            for f in val[5]:
                                for g in val[6]:
                                    for h in val[7]:
                                        Field.get(self, [a, b, c, d, e, f, g, h])

Thanks in advance!

Try this

from itertools import product
a = [[0, 1],[3, 8, 10]]
res = [list(lst) + [0] * (8 - len(lst)) for lst in product(*a)]
print(res)

Output:

[[0, 3, 0, 0, 0, 0, 0, 0], [0, 8, 0, 0, 0, 0, 0, 0], [0, 10, 0, 0, 0, 0, 0, 0], [1, 3, 0, 0, 0, 0, 0, 0], [1, 8, 0, 0, 0, 0, 0, 0], [1, 10, 0, 0, 0, 0, 0, 0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM