在两个字典之间的python列表中添加值

时间:2018-11-13 19:26:08

标签: python list loops dictionary sum

我有一个整数列表。在该列表中,有两个像这样的字典:

value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]

我要获取的输出是两个字典之间的值之和,以及字典的值。例如:

for item in value_list:
     # if item in list is a dict, sum its value
     # with value of next dict and values in between

在这种情况下,输出将为5780

我想到的一种方法是找到两个字典的索引号并像这样使用它们:

value_list[3]['low'] + sum(value_list[4:7]) + value_list[7]['low']

但这似乎太令人费解了

6 个答案:

答案 0 :(得分:1)

您可以使用以下代码,假设您拥有的唯一类型是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

答案 1 :(得分:0)

您可以使用带有标志变量的循环

found_dict = False
total = 0
for i in value_list:
    if found_dict:
        if type(i) is dict:
            total += i['low']
            break
        else:
            total += i
    elif type(i) is dict:
        total += i['low']
        found_dict = True

答案 2 :(得分:0)

假设value_list的第一个和最后一个字典之间只有数字值:

value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
dicts = [(i, list(d.values())[0]) for i, d in enumerate(value_list) if isinstance(d, dict)]
sum(value_list[dicts[0][0] + 1 : dicts[-1][0]]) + sum(t[-1] for t in dicts)
# Outputs: 5780

如果假设不正确,则需要更复杂。

答案 3 :(得分:0)

如果您有dict对象的索引(索引?),则可以在列表理解中使用它们:

sum([x if type(x)==int else x['low'] for x in value_list[3:8]])

答案 4 :(得分:0)

快速而懒惰的解决方案,尽管我确定我会因为无法正确捕获和处理异常而感到不适

fl = 0
s = 0
for i in value_list:
    if fl == 0:
        if type(i) == dict:
             s += i['low']
             fl = 1
             continue
    if fl == 1:
        try:
            s += i
        except:
            s += i['low']
            fl = 0

答案 5 :(得分:0)

您可以提取字典的索引,并在需要时使用函数提取值

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]))