简体   繁体   English

Python:如何解决TypeError:循环中需要整数

[英]Python: how resolve TypeError: an integer is required in a loop

I have a list Dsr 我有清单Dsr

>>> Dsr
[59.10346189206572, 40.4211078871491, 37.22898098099725]
type(Dsr)
<type 'list'>

I need to calculate the max value and divide each element of the list for this value 我需要计算最大值并将该值除以列表中的每个元素

dmax = numpy.max(Dsr)
RPsr = []
for p in xrange(Dsr):
      RPsr.append(float(Dsr[p]/dmax))

I have the following questions: 我有以下问题:

1) when i run this loop i got thie error message: 1)当我运行此循环时,我收到错误消息:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: an integer is required

2) is it possible to convert the loop in a most elegant list comprehension? 2)是否可以以最优雅的列表理解方式转换循环?

You're getting the exception because xrange() takes an int and not a list . 因为xrange()需要一个int而不是一个list所以您得到了例外。 You need to use len() : 您需要使用len()

for p in xrange(len(Dsr)):
                ^^^

Since you're already using NumPy, my advice would be to rewrite the whole thing like so: 由于您已经在使用NumPy,我的建议是像这样重写整个过程:

In [7]: Dsr = numpy.array([59.10346189206572, 40.4211078871491, 37.22898098099725])

In [8]: Dsr / Dsr.max()
Out[8]: array([ 1.        ,  0.68390423,  0.6298951 ])

If I understood you correctly, you need this: 如果我对您的理解正确,那么您需要这样做:

>>> dsr = [59.10346189206572, 40.4211078871491, 37.22898098099725]
>>> the_max = max(dsr)
>>> [i/the_max for i in dsr] 
[1.0, 0.6839042349323938, 0.6298950990211796]

Presumably you want to iterate over the actual list. 大概您想遍历实际列表。 You don't use xrange for that: 您不为此使用xrange

for p in Dsr:
    RPsr.append(float(p/dmax))

And you're correct that a list comprehension is the simpler way: 而且您是正确的,列表理解是更简单的方法:

RPsr = [p/dmax for p in Dsr]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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