我有一个这样的字典,比显示的多出数千个键,每个字母有数百个值a
,b
,c
:
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
求和。例如,对于a
的cat
条目,操作是(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
我不知道如何得到一个聪明的方式,不需要大量的手动输入每个条目,然后输出到上面的形式
如果您可以使用
pandas
库,那么可以非常顺利地编写它通常将列表放入数据帧不是一个好主意,但是我们只做一些轻微的处理,然后将结果保存到csv文件中
这将导致文件
您可以定义一个单独的方法来获取列表中所有列表的第2个和第1个元素之间的所有差异的总和,然后使用“dictionary conservation”生成
result
:输出
要将其写入CSV文件,可以使用^{} 模块:
输出
如果你发现自己不得不一遍又一遍地做某个计算,那么这时最好写一个函数。下面是一个函数,它接受dictex之类的字典、动物名称和字母,并为您返回单独的计算结果:
下面是一个函数,它遍历整个字典,计算每个动物和字母的值,最后返回如下列表中的结果:
[ ['cat',7,9,10], ['dog',8,10,9], ... ]
等等我之所以使用上述格式,是因为这样可以更容易地将结果写入csv文件。只需获取上一个函数中的每个列表,用逗号将所有内容连接在一起,并将其作为一行写入文件:
请记住,Python中的字典是没有顺序的。因此,生成的文件中的动物行的顺序不一定与原始词典中的动物行的顺序相同
相关问题 更多 >
编程相关推荐