简体   繁体   English

适用于循环200到205的Python整数

[英]Python Integer for loop 200 to 205

I need to input a list of http-response codes into my application config and want to provide a python shorthand so they won't list off each single code. 我需要在我的应用程序配置中输入一个HTTP响应代码列表,并想提供一个python速记,这样它们就不会列出每个单独的代码。

something like the following: 类似于以下内容:

class settings: 
  success_codes= 200..299        # successful request
  retry_codes= 400..404,500-503  # retry later
  fail_codes = 504,505,506       # don't retry again 

doesn't python support some kind of clean syntax like this to define ranges? python不支持像这样的干净语法来定义范围吗? I need multiple ranges. 我需要多个范围。

Use ranges , in Python 2.x: 在Python 2.x中使用ranges

success_codes = range(200, 300)
retry_code    = range(400, 405) + range(500, 504)
fail_codes    = range(504, 507)

And for reference, in Python 3.x (also works in Python 2.x): 作为参考,在Python 3.x中(在Python 2.x中也适用):

success_codes = list(range(200, 300))
retry_code    = list(range(400, 405)) + list(range(500, 504))
fail_codes    = list(range(504, 507))

只需使用range函数:

vals = range(start, stop + 1)

This works across all versions of python 这适用于所有版本的python

class settings: 
  success_codes = list(range(200, 299 + 1)) # successful request
  retry_codes = list(range(400, 404 + 1)) + list(range(500, 503 + 1)) # retry later
  fail_codes = list(range(504, 506 + 1)) # don't retry again

In earlier versions of python, list(range()) can be replaced by range() . 在python的早期版本中, list(range())可以被range()代替。 Also, obviously, you can add the 1 to the upper value directly. 同样,显然,您可以将1直接加到上限值。

Using range(n, m+1), like a lot of people are suggesting, works. 就像很多人建议的那样,使用range(n,m + 1)可以工作。 However, do you need to create all the possible values in memory? 但是,您是否需要在内存中创建所有可能的值?

In most cases you can use: 在大多数情况下,您可以使用:

if return_code < 200 or return_code >= 299:
    do_something()

Or: 要么:

if return_code in range(200, 299+1):
    do_something()

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

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