简体   繁体   中英

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

I have a list 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:

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?

You're getting the exception because xrange() takes an int and not a list . You need to use len() :

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

Since you're already using NumPy, my advice would be to rewrite the whole thing like so:

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:

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]

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