我有太多的if语句,我很难理解字典系统。
这似乎很容易解决,但我尝试的一切都会使情况变得更糟。
"""
Find the place where the person was born.
Possible locations are following: Kuressaare, Tartu, Tallinn, Kohtla-Järve, Narva, Pärnu,
Paide, Rakvere, Valga, Viljandi, Võru and undefined. Lastly if the number is incorrect the function must return
the following 'Wrong input!'
:param birth_number: int
:return: str
"""
return
if not is_valid_birth_number(birth_number):
return "Wrong input!"
if 10 >= birth_number >= 1:
return "Kuressaare"
elif 20 >= birth_number >= 11:
return "Tartu"
elif 220 >= birth_number >= 21:
return "Tallinn"
elif 270 >= birth_number >= 221:
return "Kohtla-Järve"
elif 370 >= birth_number >= 271:
return "Tartu"
elif 420 >= birth_number >= 371:
return "Narva"
elif 470 >= birth_number >= 421:
return "Pärnu"
elif 490 >= birth_number >= 471:
return "Tallinn"
elif 520 >= birth_number >= 491:
return "Paide"
elif 570 >= birth_number >= 521:
return "Rakvere"
elif 600 >= birth_number >= 571:
return "Valga"
elif 650 >= birth_number >= 601:
return "Viljandi"
elif 710 >= birth_number >= 651:
return "Võru"
elif 999 >= birth_number >= 711:
return "undefined"
需要摆脱idcode.py:149:1: C901 'get_birth_place' is too complex (16)
错误。
使用将每个范围的末尾映射到返回值的列表。
if not is_valid_birth_number(birth_number):
return "Wrong input!"
locations = [(10, "Kuressaare"), (220, "Tartu"), (270, "Tallinn"), ...]
for limit, loc in locations:
if birth_number <= limit:
return loc
您不需要每个范围的开头和结尾,因为它们是按顺序排列的。只要范围的尽头就足够了。
一个带有bisect
的例子。
import bisect
locations = {
1: 'Kuressaare',
2: 'Tartu',
3: 'Tallinn',
4: 'Kohtla-Järve',
5: 'Tartu'
}
birth_number_levels = [1, 11, 21, 221, 271, 371]
position = bisect.bisect(birth_number_levels, birth_number)
return locations[position]
我更喜欢像@Barmar那样将数据放在一起。这导致:
import bisect
locations = [
(10, 'Kuressaare'),
(20, 'Tartu'),
(220, 'Tallinn'),
(270, 'Kohtla-Järve'),
(370, 'Tartu')
]
birth_number_levels = [location[0] for location in locations]
position = bisect.bisect_left(birth_number_levels, birth_number)
return locations[position][1]
我会使用字典,其中包含键作为范围,值是位置的名称。 然后遍历它,检查给定的birth_number
是否在密钥中。
基本上:
loc_dict = {
range(1, 11): "Kuressaare",
range(11, 21): "Tartu",
etc...
}
for loc_range, loc_name in loc_dict.items():
if birth_number in loc_range:
return loc_name
我认为这是一种非常清晰的处理方式。
遍历列表比编写特定的 if 语句更容易,而且这可以是完全动态的。
def bd(birth_number):
x = ((10,"Kuressaare"),(20,"Tartu"),(220,"Tallinn"),(270,"Tartu"),(370,"Kohtla-Järve"),(420,"Tartu"),(470,"Narva"),(490,"Pärnu"),(520,"Tallinn"),(570,"Paide"),(600,"Rakvere"))
if not isinstance(birth_number, (int, long)):
return "Wrong input!"
for i in x:
if birth_number<= i[0]:
return i[1]
return "undefined"
print(bd(300))