有什么办法可以使if语句更短,更清晰?

时间:2018-11-10 08:43:45

标签: python string python-3.x if-statement operators

我有很长的if语句,以查看字符串是否等于最大为9的任何数字。但是它是如此之长,并且占用大量空间。有什么方法可以使它更短更清洁?我是编程新手。

if calculated == "1" or calculated == "2" or calculated == "3" or calculated == "4" or calculated == "5" or calculated == "6" or calculated == "7" or calculated == "8" or calculated == "9":

3 个答案:

答案 0 :(得分:8)

是,请尝试以下操作:

if calculated in ['1','2','3',...,'9']:
    # do

或者您可以这样做:

if calculated in [str(i) for i in range(1, 10)]:
    # do

这种方式也是可能的:

if calculated in list(map(str, range(1, 10))):
   # do

答案 1 :(得分:3)

闻起来像XY problem。如果您知道字符串是数字,则应将其转换为数字并使用基于整数的逻辑:

if 1 <= int(calculated) <= 9:
    pass

但是,如果由于某些原因而无法解决问题,您的逻辑可以简化为检查范围:

if calculated in (str(n) for n in range(1, 10)):
    pass

答案 2 :(得分:2)

或者,在这种简单情况下,

try:
    if int(calculated) in range(1, 10):

反之亦然:

if calculated in map(str, range(1, 10)):