错误不能将序列乘以'float'类型的非int

时间:2014-04-25 15:13:34

标签: python

我收到以下错误:

     if len(new_send_times) > rate_limit * window * self._throttle:
        TypeError: can't multiply sequence by non-int of type 'float'

这是代码:

if len(new_send_times) > rate_limit * window * self._throttle:
                    # Sleep the remainder of the window period.
                    delta = now - new_send_times[0]
                    total_seconds = (delta.microseconds + (delta.seconds +
                                                           delta.days * 24 * 3600) * 10 ** 6) / 10 ** 6
                    delay = window - total_seconds
                    if delay > 0:
                        sleep(delay)

                recent_send_times.append(now)
                # end of throttling

它使用的值是

if len([]) > 1.0 * 2.0 * 0.5:

更新 我将其更改为下方并且可以正常工作,但我仍然不理解错误或者我是否想要这样做:

 if len(new_send_times) > float(rate_limit) * float(window) * float(self._throttle):

2 个答案:

答案 0 :(得分:2)

错误非常自我表达。您正在以

的形式执行操作
list * float # or other sequence * float

在python中是禁止的,你可以

numeric * float # "traditional" multiplication

list * int # creates concatenated copies of the list provided

因此,请调查您的代码,检查哪个对象是列表并将其转换为数字,因为代码逻辑表明这是您的预期行为。

示例:

[1] * 3 = [1,1,1]

[1] * 1.5 # ERROR

1 * 1.5 == 1.5

float([1]) * 1.5 == 1.5

"1" * 1.5 # ERROR

float("1") * 1.5 == 1.5

答案 1 :(得分:1)

错误消息

TypeError: can't multiply sequence by non-int of type 'float'

告诉你至少有一个

len(new_send_times), rate_limit, window, self._throttle

不是你怀疑的数字,而是某种顺序。

print这些值并看到你期望的事实,以及在值上使用float()使代码工作的事实强烈暗示其中一个是字符串表示形式一个数字(例如'1.0')而不是数字本身 - Python中的str计为sequence

len()将始终返回int(或引发错误!),因此无需担心,但其他三个中的一个可能是一个字符串。您需要获取值的来源([raw_]input?解析文件?)并确保它们在适当的位置转换为数字类型(越早越好,因为在其他情况下您可能获得更多微妙的问题)。

要说明差异,在print要检查的值时,您可以执行以下操作:

print(rate_limit, type(rate_limit))