我有一段非常讨厌的代码我想重构,但我有,因为它变得完全不可读。
for region in feed['config']['regions']:
if region['region'] == region_name:
for instance_type in region['instanceTypes']:
if instance_type['type'] == instance_type_name:
for instance_size in instance_type['sizes']:
if instance_size['size'] == instance_size_name:
for platform in instance_size['valueColumns']:
if platform['name'] == platform_name:
prices = platform['prices']
assert prices.keys() == ['USD']
return decimal.Decimal(prices['USD'])
assert False, "Failed to determine price for instance with region=%r, type=%r, size=%r, platform=%r" % \
(region_name, instance_type_name, instance_size_name, platform_name)
我一直在为每个循环或 if 语句使用函数,但这会给我带来很多函数。有更好的解决方案吗?