Python简化

时间:2013-12-10 14:55:27

标签: python simplification

Birth_date是1到2359之间的整数。每只动物也是一个列表的一部分。我想将出生日期转换为列表索引,但我不确定如何。

if (birth_time >= 2300) or (birth_time < 100):
    hour_animal = "RAT"
elif (birth_time >= 100) and (birth_time < 300):
    hour_animal = "OX"
elif (birth_time >= 300) and (birth_time < 500):
    hour_animal = "TIGER"
elif (birth_time >= 500) and (birth_time < 700):
    hour_animal = "RABBIT"
elif (birth_time >= 700) and (birth_time < 900):
    hour_animal = "DRAGON"
elif (birth_time >= 900) and (birth_time < 1100):
    hour_animal = "SNAKE"
elif (birth_time >= 1100) and (birth_time < 1300):
    hour_animal = "HORSE"
elif (birth_time >= 1300) and (birth_time < 1500):
    hour_animal = "SHEEP"
elif (birth_time >= 1500) and (birth_time < 1700):
    hour_animal = "MONKEY"
elif (birth_time >= 1700) and (birth_time < 1900):
    hour_animal = "ROOSTER"
elif (birth_time >= 1900) and (birth_time < 2100):
    hour_animal = "DOG"
elif (birth_time >= 2100) and (birth_time < 2300):
    hour_animal = "BOAR"

有关如何简化这一点的任何想法?

谢谢!

4 个答案:

答案 0 :(得分:2)

如果您的列表以RAT开头,则索引应为(birth_time + 100) // 200 % 12

但要更好地验证它:

signs = ['rat', 'ox', 'tiger', 'rabbit', 'dragon', 'snake', 'horse', 'sheep', 'monkey', 'rooster', 'dog', 'boar']

while True:
    time = int(input('>> '))
    print(signs[(time + 100) // 200 % 12])

答案 1 :(得分:0)

第1步:

if birth_time < 100:
    hour_animal = "RAT"
elif birth_time < 300:
    hour_animal = "OX"
elif birth_time < 500:
    hour_animal = "TIGER"
elif birth_time < 700:
    hour_animal = "RABBIT"
elif birth_time < 900:
    hour_animal = "DRAGON"
elif birth_time < 1100:
    hour_animal = "SNAKE"
elif birth_time < 1300:
    hour_animal = "HORSE"
elif birth_time < 1500:
    hour_animal = "SHEEP"
elif birth_time < 1700:
    hour_animal = "MONKEY"
elif birth_time < 1900:
    hour_animal = "ROOSTER"
elif birth_time < 2100:
    hour_animal = "DOG"
elif birth_time < 2300:
    hour_animal = "BOAR"
else:
    hour_animal = "RAT"

请注意,我在开始和结束时将RAT放入两次,这让我删除了一半的条件。

步骤2:注意这些数字是100的倍数,并且距离200的倍数是100。所以@Hyperboreus的解决方案(他在我打字时提交了它)。

答案 2 :(得分:0)

你可以用最小和最大时间设置一个dict,并默认返回“RAT”:

birth_times = {"OX": {"min":100, "max":300},
               "TIGER": {"min":300, "max":500},
               ...
               }

def animal(btime):
    return ([k for k in birth_times.keys()
             if birth_times[k]["min"] <= btime < birth_times[k]["max"]]
            + ["RAT"])[0]

答案 3 :(得分:0)

您可以在此处使用bisect模块。此处bisect.bisect_right O(日志N)时间内找到特定索引,因此您的if - elif链仅缩减为一个{{1} }}:

if

<强>演示:

import bisect

def solve(lis1, lis2, n):
    ind = bisect.bisect_right(lis1, n) - 1
    if 0 <= ind < len(lis1)-1:
        return lis2[ind]
    return 'RAT'

birth_time = [100, 300, 500, 700, 900, 1100, 1300, 1500, 1700, 1900, 2100, 2300]

hour_animal = ['OX', 'TIGER', 'RABBIT', 'DRAGON', 'SNAKE', 'HORSE', 'SHEEP', 'MONKEY', 'ROOSTER', 'DOG', 'BOAR']