3 回答
TA贡献1851条经验 获得超3个赞
您可以使用以下代码,假设您拥有的唯一类型是 int 和 dict,并且 dict 将始终具有相同的格式:
total_sum = 0
dicts_num = 0 #flag for checking how many dicts have appeared
for value in value_list:
if isinstance(value, dict):
dicts_num += 1
total_sum += value["low"]
elif (dicts_num == 1):
total_sum += value
TA贡献1786条经验 获得超11个赞
您可以提取字典的索引,并在需要时使用函数来提取值
def int_or_value(item, key='low'):
if isinstance(item, int):
return item
else:
return item[key]
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
indices = [index for index, value in enumerate(value_list) if isinstance(value, dict)]
# Use this if you have multiple instances of {dict} ... {dict} to sum in you value_list
for start, stop in (indices[n:n+2] for n in range(0, len(indices), 2)):
print(sum(int_or_value(item) for item in value_list[start:stop+1]))
# If you are sure there is going to be a single instance of {dict} ... {dict} to sum just access indices directly
print(sum(int_or_value(item) fro item in value_list[indices[0]:indices[1]+1]))
添加回答
举报