我有一些数据数组:
a = numpy.array([[ 1, 2, 3, 4],
[ 10, 20, 30, 40],
[100, 200, 300, 400]])
并使用a
创建字典
:
d = dict(zip( ['a', 'b', 'c'], a))
所以:
print(d)
{'a': array([1, 2, 3, 4]), 'b': array([10, 20, 30, 40]), 'c': array([100, 200, 300, 400])}
据我所知,Python 3.x 字典中的元素顺序是恒定的。因此,据我了解,如果 a
是 d
中的第一个元素,它总是第一个。
我的问题,如果我的推理是正确的,是否有任何方法可以使用索引号来引用元素?
我知道我做不到
d[0]
因为里面没有 0
键。但也许有某种方法:d{0}
或 d.values[0]
。
最佳答案
您可以访问list(d.values())[0]
,但是您可能会得到不同的值
每次执行脚本时(实际上,每次重新启动解释器时),所以您真的不应该这样做/依赖于此。
λ python3
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'a': 1, 'b': 2}
>>> list(d.values())[0]
2
>>> exit()
λ python3
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'a': 1, 'b': 2}
>>> list(d.values())[0]
1
>>> exit()
如果您确实想要这种行为,您可以使用 OrderedDict
。
λ python3
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>> d = OrderedDict({'a': 1, 'b': 2})
>>> list(d.values())[0]
1
>>> exit()
λ python3
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>> d = OrderedDict({'a': 1, 'b': 2})
>>> list(d.values())[0]
1
>>> exit()
关于python - 通过索引号引用字典元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46910370/