开发者

decimal range in for

Sorry for my beginner question. I want to construct decimal range step in for cycle using the following construction:

max_value = 10
my_range = [r * 0.01 for r in r开发者_高级运维ange(0, max_value) ]
    for i in range ( my_range ): //Error
         print (i)

But there is the following error:

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


Your my_range is already a list. Just do:

for i in my_range:
    print(i)


The error appears because range() function accepts three arguments: starting value (included in iteration), end value (not included) and a step. From mathematical point of view, it's: [a1, a2, ... an) where d = a2 - a1 is the step.

So, my_range = [r * 0.01 for r in range(0, max_value) ] creates a list. And naturally, range() can't accept a list as an argument.

In case, if you need [0.01, 0.02, ... 10]:

step = 0.01
max_val = 10
for i in range(0, max_val / step + 1):
    print i * step


Try

for i in my_range:
  print(i)

You've create the my_range list, which you can iterate over with for. You don't need to call range() again.

The range() function accepts integers as parameters, but running range(my_range) passes in your list, which results in this error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜