2024-04-20 04:17:04 发布
网友
我有一个python字典的键,我想在字典中得到相应的索引。假设我有下列字典
d = { 'a': 10, 'b': 20, 'c': 30}
是否有python函数的组合,以便在给定键值“b”的情况下获得索引值1?
d.??('b')
我知道可以通过一个循环或lambda(嵌入一个循环)来实现。只是觉得应该有一个更直接的方法。
不,没有直接的方法,因为Python字典没有集合顺序。
从documentation:
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.
换言之,b的“索引”完全取决于之前插入和删除的映射:
b
>>> map={} >>> map['b']=1 >>> map {'b': 1} >>> map['a']=1 >>> map {'a': 1, 'b': 1} >>> map['c']=1 >>> map {'a': 1, 'c': 1, 'b': 1}
从Python2.7开始,如果插入顺序对应用程序很重要,则可以使用^{} type。
使用OrderedDicts:http://docs.python.org/2/library/collections.html#collections.OrderedDict
>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2"))) >>> x["d"] = 4 >>> x.keys().index("d") 3 >>> x.keys().index("c") 1
对于那些使用Python 3的用户
>>> list(x.keys()).index("c") 1
python中的字典没有顺序。您可以使用元组列表作为数据结构。
d = { 'a': 10, 'b': 20, 'c': 30} newd = [('a',10), ('b',20), ('c',30)]
然后此代码可用于查找具有特定值的键的位置
locations = [i for i, t in enumerate(newd) if t[0]=='b'] >>> [1]
不,没有直接的方法,因为Python字典没有集合顺序。
从documentation:
换言之,
b
的“索引”完全取决于之前插入和删除的映射:从Python2.7开始,如果插入顺序对应用程序很重要,则可以使用^{} type 。
使用OrderedDicts:http://docs.python.org/2/library/collections.html#collections.OrderedDict
对于那些使用Python 3的用户
python中的字典没有顺序。您可以使用元组列表作为数据结构。
然后此代码可用于查找具有特定值的键的位置
相关问题 更多 >
编程相关推荐