【问题标题】:Problem with iterating when using variable length python function arguments使用可变长度 python 函数参数时的迭代问题
【发布时间】:2019-12-10 20:58:23
【问题描述】:
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)  

如果我运行上面的代码,它会说:

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

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

和:

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

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

此问题在窗口长度可变(即 *windows 而不仅仅是窗口)时发生。

我该如何解决这个问题?这是什么原因造成的?

【问题讨论】:

  • 当你只运行函数定义不会引发错误,你能否提供一个最小的示例代码调用函数抛出错误?问题显然在于未显示的输入数据的格式。
  • 方法怎么调用?
  • windows 变量的一些示例值是什么?
  • @azro 好点了吗?
  • @TadhgMcDonald-Jensen 好点了吗?

标签: python python-3.x function variables args


【解决方案1】:

max 函数需要传递多个参数,而不是包含多个参数的元组。您的 windows 变量是一个元组。

所以,不是:

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

改为这样做:

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

关于您的第二个错误,涉及以下行:

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

好的,你在做减法,它抱怨你不能从一个整数中减去一个列表。而且由于我不知道windows[j] 包含什么,我不能说那里是否有一个列表.. 但如果有,就不会有。你还没有给我们一个可行的例子来尝试。

我建议你在你的代码中加入一些调试输出,例如:

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

然后看看你的数据是什么样子的。

【讨论】:

  • 这解决了第一个问题。抱歉,最初忘记在问题中提出第二个(相关)问题
  • 你传递给函数的是什么?
猜你喜欢
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
相关资源
最近更新 更多