在python中对字典的字母数字值进行排序

时间:2018-05-22 05:22:10

标签: python sorting dictionary

我正在尝试在python中对字典进行排序,如下所示: 在这种情况下,我的词典有“ESPN”,“AAA”是键,值在

之下
'ESPN': [
    'ESPN 90 TO 100_1050',
    'ESPN 60 TO 70_1150',
    'ESPN 80 TO 90_1250',
    'ESPN 90 TO 100_1750',
    'ESPN 90 TO 100_900'
    'ESPN 90 TO 100_1650',
    'ESPN 70 TO 80_1350',
    'ESPN 20 TO 30_1450'
]

'AAA': [
    'AAA 90 TO 100_1050',
    'AAA 60 TO 70_1150',
    'AAA 80 TO 90_1250',
    'AAA 90 TO 100_1750',
    'AAA 90 TO 100_1650',
    'AAA 70 TO 80_1350',
    'AAA 20 TO 30_1450'
]

我试图按照这样的方式对这个词典进行排序,以便我希望ESPN和AAA之后的数字以递增的方式以及下划线之后的数字。

例如如下

'ESPN': [
    'ESPN 20 TO 30_1450',
    'ESPN 60 TO 70_1150',
    'ESPN 70 TO 80_1350',
    'ESPN 80 TO 90_1250',
    'ESPN 90 TO 100_900',
    'ESPN 90 TO 100_1650',
    'ESPN 90 TO 100_1750',
]

我正在尝试正则表达式并排序,但我无法得到它。如果有人能提供帮助,真的很感激。我也尝试了各种排序技术,但我总是最终排序键而不是值。 此外,在大多数情况下,它没有按预期工作,因为当我的值为AAA 20到30_900时,它在AAA 20到30_1450之前没有按顺序排列,而是在它之后。

TIA

3 个答案:

答案 0 :(得分:1)

这是使用连续str.split次呼叫的一种方式。映射到整数可确保900在1000之前出现。

def sorter(x):
    _, var1, _, var2 = x.split()
    var2a, var2b = var2.split('_')
    return list(map(int, (var1, var2a, var2b)))

res = sorted(d['ESPN'], key=sorter)

['ESPN 20 TO 30_1450',
 'ESPN 60 TO 70_1150',
 'ESPN 70 TO 80_1350',
 'ESPN 80 TO 90_1250',
 'ESPN 90 TO 100_900',
 'ESPN 90 TO 100_1050',
 'ESPN 90 TO 100_1650',
 'ESPN 90 TO 100_1750']

答案 1 :(得分:0)

d = {
    'ESPN': [
        'ESPN 90 TO 100_1050',
        'ESPN 60 TO 70_1150',
        'ESPN 80 TO 90_1250',
        'ESPN 90 TO 100_1750',
        'ESPN 90 TO 100_1650',
        'ESPN 70 TO 80_1350',
        'ESPN 20 TO 30_1450'
    ],
    'AAA': [
        'AAA 90 TO 100_1050',
        'AAA 60 TO 70_1150',
        'AAA 80 TO 90_1250',
        'AAA 90 TO 100_1750',
        'AAA 90 TO 100_1650',
        'AAA 70 TO 80_1350',
        'AAA 20 TO 30_1450'
    ]
}
[v.sort() for v in d.values()]

结果:

{'AAA': ['AAA 20 TO 30_1450',
  'AAA 60 TO 70_1150',
  'AAA 70 TO 80_1350',
  'AAA 80 TO 90_1250',
  'AAA 90 TO 100_1050',
  'AAA 90 TO 100_1650',
  'AAA 90 TO 100_1750'],
 'ESPN': ['ESPN 20 TO 30_1450',
  'ESPN 60 TO 70_1150',
  'ESPN 70 TO 80_1350',
  'ESPN 80 TO 90_1250',
  'ESPN 90 TO 100_1050',
  'ESPN 90 TO 100_1650',
  'ESPN 90 TO 100_1750']}

答案 2 :(得分:0)

您可以使用re.findall提取所有连续的数字序列,转换为整数并应用字典排序。

key = lambda s: tuple(map(int, re.findall('\d+', s)))
result = {k: sorted(v, key=key) for k, v in data.items()}

# Output

In [156]: result
Out[156]: 
{'AAA': ['AAA 20 TO 30_1450',
  'AAA 60 TO 70_1150',
  'AAA 70 TO 80_1350',
  'AAA 80 TO 90_1250',
  'AAA 90 TO 100_1050',
  'AAA 90 TO 100_1650',
  'AAA 90 TO 100_1750'],
 'ESPN': ['ESPN 20 TO 30_1450',
  'ESPN 60 TO 70_1150',
  'ESPN 70 TO 80_1350',
  'ESPN 80 TO 90_1250',
  'ESPN 90 TO 100_900',
  'ESPN 90 TO 100_1050',
  'ESPN 90 TO 100_1650',
  'ESPN 90 TO 100_1750']}