【问题标题】:Sorting alphanumeric keys of a dictionary in python在python中对字典的字母数字键进行排序
【发布时间】:2013-07-27 03:14:56
【问题描述】:

我有一个 python 字典,其键具有以下模式

<some x number of digits/alphabets> <some y number of alphabets><some z number of digits>

我想根据这个键对字典进行排序。 例如

01IB0610, 01IB062, 01IB064

应该是01IB062, 01IB064 01IB0610

完整的例子是这样的:

{ '01IB0610' : {'a' : [] , 'b': [] }, '01IB062' : {'a' : [] , 'b': [] } , '01IB064' : {'a' : [] , 'b': [] }

最终输出应该是:{ '01IB062' : {'a' : [] , 'b': [] }, '01IB064' : {'a' : [] , 'b': [] } , '01IB0610' : {'a' : [] , 'b': [] }

【问题讨论】:

标签: python regex dictionary


【解决方案1】:
import re

def key_func(s):
    return [int(x) if x.isdigit() else x for x in re.findall(r'\D+|\d+', s)]

sorted_keys = sorted(d, key=key_func)

例子:

>>> d = {'01IB0610': 'foo', '01IB062': 'bar', '01IB0604': 'baz'}
>>> sorted(d, key=key_func)
['01IB062', '01IB0604', '01IB0610']

【讨论】:

  • 你应该明确地说返回了一个新列表 - 与 list.sort() 不同,它不使用 dict 并且有些如何给它排序。
  • 我没有添加 dict of dict 的事实。关键是第一个字典
  • @gizgok 请用您当前的字典和您希望得到的最终结果给出一个完整的例子。
  • @F.J 我加了一个例子
  • Python 中的字典无法排序。您可以使用collections.OrderedDict,它可以按特定顺序保留键,或者您可以按照我的答案对键进行排序,然后使用该结果根据该顺序访问字典值。
【解决方案2】:

我不确定我是否完全了解排序标准,但您可以使用OrderedDict 来设置保持特定顺序的dict

from collections import OrderedDict
import re
d = {'01IB0610': 1, '01IB062': 2, '01IB064': 3}

def criteria(x):
    number = int(re.sub('[^0-9]', '', x[0]) )
    length = len(x[0])
    return length, number
d = OrderedDict( sorted( d.items(), key = criteria ) )
d.keys()
>> ['01IB062', '01IB064', '01IB0610']

这将创建一个OrderedDict,其中原始dict 中元素的顺序基于这些元素的键的分层排序。第一个标准是密钥的长度,即01IB061001IB064 之后,因为它更长。第二个条件是基于密钥中的数字,即0106201064 之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多