Python:如何将字典转换为可下标的数组? [英] Python: how to convert a dictionary into a subscriptable array?

查看:146
本文介绍了Python:如何将字典转换为可下标的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在Python中将字典转换为列表,但是以某种方式尝试获取结果列表的总和时,出现错误'dict_values' object is not subscriptable.另外,我打算只对列表中的几项进行汇总.

I know how to convert a dictionary into an list in Python, but somehow when I try to get, say, the sum of the resulting list, I get the error 'dict_values' object is not subscriptable. Also, I plan to sum only several items in the list.

dict = {A:1, B:2, C:3, D:4}
arr = dict.values()
the_sum = sum(arr[1:3])

在仔细检查后,我注意到在打印出结果列表时,它始终给出dict_values(......)作为我无法删除的输出.我该如何解决?

Upon closer inspection, I noticed that when the resulting list is printed out, it always gives dict_values(......) as the output which I can't remove. How do I get around this?

推荐答案

在python-3.X中,dict.values不会像在python-2.X中那样返回list.在python-3.x中,它返回一个dict-value对象,它是一个类似于集合的对象,并使用哈希表存储其项目.除了支持大多数set属性外,此功能还针对某些操作(例如成员资格检查(使用in运算符))进行了优化.因此,它不支持索引.

In python-3.X dict.values doesn't return a list like how it performs in python-2.X. In python-3.x it returns a dict-value object which is a set-like object and uses a hash table for storing its items. This feature, in addition to supporting most of set attributes, is very optimized for some operations like membership checking (using in operator). And because of that, it doesn't support indexing.

如果要获取列表对象,则需要通过将结果传递给list()函数将其转换为列表.

If you want to get a list object, you need to convert it to list by passing the result to the list() function.

the_values = dict.values()
SUM = sum(list(the_values)[1:10])

这篇关于Python:如何将字典转换为可下标的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆