Search code examples
pythonpython-3.xfunctionvariablesargs

Problem with iterating when using variable length python function arguments


def function1(self,*windows):
    xxx_per_win = [[] for _ in windows]

    for i in range(max(windows),self.file.shape[0]):
        for j in range(len(windows)): 
            zz = self.file['temp'][i-windows[j]:i].quantile(0.25)
            ...
            ...
            ...

o = classX(file)
windows = [3,10,20,40,80]
output = o.function1(windows)  

If I run the code above it says:

for i in range(max(windows),self.file.shape[0]):

TypeError: 'list' object cannot be interpreted as an integer

and:

zz = self.file['temp'][i-windows[j]:i].quantile(0.25)

TypeError: unsupported operand type(s) for -: 'int' and 'list'

This problem only occurs when windows is variable length (ie *windows and not just windows).

How do I fix this? What is causing this?


Solution

  • The max function expects to be passed multiple arguments, not a tuple containing multiple arguments. Your windows variable is a tuple.

    So, not:

    for i in range(max(windows),self.file.shape[0]):
    

    Do this instead:

    for i in range(max(*windows),self.file.shape[0]):
    

    On your second error, involving the line:

    zz = self.file['temp'][i-windows[j]:i].quantile(0.25)
    # TypeError: unsupported operand type(s) for -: 'int' and 'list'
    

    Ok, you are subtracting, and it's complaining that you can't subtract a list from an integer. And since I have no idea what windows[j] contains, I can't say whether there's a list in there or not.. but if there is, there can't be. You haven't given us a working example to try.

    What I suggest you do is to put some debugging output in your code, eg:

    print('i=%s, j=%s, windows[j]=%s' % (i, j, windows[j]))
    

    and thus see what your data looks like.