简体   繁体   English

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

[英]Adding the values in a python list in between two dictionaries

I have list of integers. 我有整数列表。 In that list there are two dictionaries like so: 在该列表中有两个类似的字典:

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

The output I am trying to get is the sum of the values in between the two dictionaries, as well as the values of the dictionaries. 我想要获得的输出是两个字典之间的值之和,以及字典的值。 For example: 例如:

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

In this case the output would be 5780 在这种情况下,输出为5780

One method I thought of is finding the index number of the two dicts and using them like this: 我想到的一种方法是找到两个字典的索引号并像这样使用它们:

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

But that seems way too convoluted 但这似乎太令人费解了

You could use the following code, assuming the only types you have are int and dict, and the dict will always have the same format: 您可以使用以下代码,假设您拥有的唯一类型是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

You can use a loop with a flag variable 您可以使用带有标志变量的循环

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

Assuming there are only numeric values between the first and last dicts in the value_list : 假设在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

If the assumption is not correct this needs to be more complex. 如果假设不正确,则需要更复杂。

如果您有字典对象的索引(索引?),则可以在列表推导中使用它们:

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

Quick and lazy solution, although I'm sure I'll catch some flak for not catching and handling exceptions properly 快速而懒惰的解决方案,尽管我确定我会因为无法正确捕获和处理异常而遇到一些麻烦

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

You can extract the indices of the dicts and use a function to extract value if needed 您可以提取字典的索引,并在需要时使用函数提取值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM