字典:从一系列字典值的第二项中减去第一项

2024-09-29 21:58:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的字典,比显示的多出数千个键,每个字母有数百个值abc

dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
          'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
          'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}

我想从每个条目的第二个值中减去第一个值,然后对所有a、所有b和所有c求和。例如,对于acat条目,操作是(5-3)+(7-2)。首选输出为(.csv):

animal a   b   c
cat    7   9   10
dog    8   10  9
moose  9   11  11

我可以通过使用

dictex['cat']['a'][0][2] - dictex['cat']['a'][0][1]`
output:
2

我不知道如何得到一个聪明的方式,不需要大量的手动输入每个条目,然后输出到上面的形式


Tags: csvmoose目的output字典字母方式条目
3条回答

如果您可以使用pandas库,那么可以非常顺利地编写它

通常将列表放入数据帧不是一个好主意,但是我们只做一些轻微的处理,然后将结果保存到csv文件中

pd.DataFrame(dictex).rename_axis('animal', 1).applymap(lambda lists: sum(l[2]-l[1] for l in lists)).T.to_csv('f.csv')

这将导致文件

animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11

您可以定义一个单独的方法来获取列表中所有列表的第2个和第1个元素之间的所有差异的总和,然后使用“dictionary conservation”生成result

def diff_sums(l):
    return sum(x[2] - x[1] for x in l)

dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
          'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
          'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}

result = {animal: {k: diff_sums(v) for k, v in num_lists.items()} for animal, num_lists in dictex.items()}
print(result)

输出

{'cat': {'a': 7, 'b': 9, 'c': 10}, 
 'dog': {'a': 8, 'b': 10, 'c': 9}, 
 'moose': {'a': 9, 'b': 11, 'c': 11}}

要将其写入CSV文件,可以使用^{}模块:

import csv

columns = ['animal', 'a', 'b', 'c']
data = [[animal] + [v[c] for c in columns[1:]] for animal, v in result.items()]
with open('mydata.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for line in [columns] + data:
        writer.writerow(line)

输出

animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11

如果你发现自己不得不一遍又一遍地做某个计算,那么这时最好写一个函数。下面是一个函数,它接受dictex之类的字典、动物名称和字母,并为您返回单独的计算结果:

# Do the calculations for a particular animal and letter
def calculate_value(mydict, animal, letter):
    W = mydict[animal][letter][0][2]
    X = mydict[animal][letter][0][1]
    Y = mydict[animal][letter][1][2]
    Z = mydict[animal][letter][1][1]

    # Do the math and convert the resulting number to a string,
    # which will save us some headaches when writing to the csv file.
    return str((W-X) + (Y-Z))

下面是一个函数,它遍历整个字典,计算每个动物和字母的值,最后返回如下列表中的结果:[ ['cat',7,9,10], ['dog',8,10,9], ... ]等等

def make_new_list(my_dict):
    new_list = []
    for animal in my_dict:
        individual_animal_list = [animal]
        for letter in ['a', 'b', 'c']:
            individual_animal_list.append(calculate_value(my_dict, animal, letter))
        new_list.append(individual_animal_list)
    return new_list

我之所以使用上述格式,是因为这样可以更容易地将结果写入csv文件。只需获取上一个函数中的每个列表,用逗号将所有内容连接在一起,并将其作为一行写入文件:

dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
          'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
          'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}

new_list = make_new_list(dictex)

with open('my_file.csv', 'w') as f:
    f.write('animal,a,b,c\n') # Write the header line
    for row in new_list:
        f.write(','.join(row))
        f.write('\n')

请记住,Python中的字典是没有顺序的。因此,生成的文件中的动物行的顺序不一定与原始词典中的动物行的顺序相同

相关问题 更多 >

    热门问题