BaB*_*ons 12 python sorting dictionary
我有一个程序返回一组具有如下排名的域:
ranks = [
{'url': 'example.com', 'rank': '11,279'},
{'url': 'facebook.com', 'rank': '2'},
{'url': 'google.com', 'rank': '1'}
]
Run Code Online (Sandbox Code Playgroud)
我试图通过提升等级对它们进行排序sorted:
results = sorted(ranks,key=itemgetter("rank"))
Run Code Online (Sandbox Code Playgroud)
但是,由于"rank"的值是字符串,因此它按字母数字而不是按升序值对它们进行排序:
1. google.com: 1
2. example.com: 11,279
3. facebook.com: 2
Run Code Online (Sandbox Code Playgroud)
我需要将"rank"键的值转换为整数,以便它们能够正确排序.有任何想法吗?
the*_*eye 19
你快到了.您需要在替换后将拾取的值转换为整数,,如下所示
results = sorted(ranks, key=lambda x: int(x["rank"].replace(",", "")))
Run Code Online (Sandbox Code Playgroud)
例如,
>>> ranks = [
... {'url': 'example.com', 'rank': '11,279'},
... {'url': 'facebook.com', 'rank': '2'},
... {'url': 'google.com', 'rank': '1'}
... ]
>>> from pprint import pprint
>>> pprint(sorted(ranks, key=lambda x: int(x["rank"].replace(",", ""))))
[{'rank': '1', 'url': 'google.com'},
{'rank': '2', 'url': 'facebook.com'},
{'rank': '11,279', 'url': 'example.com'}]
Run Code Online (Sandbox Code Playgroud)
注意:我刚用pprint函数来打印结果.
这里,x将是key确定值的当前对象.我们从中获取rank属性的值,,用空字符串替换,然后将其转换为数字int.
如果您不想更换,和正确处理它,那么您可以使用locale模块的atoi功能,如下所示
>>> import locale
>>> pprint(sorted(ranks, key=lambda x: int(locale.atoi(x["rank"]))))
[{'rank': '1', 'url': 'google.com'},
{'rank': '2', 'url': 'facebook.com'},
{'rank': '11,279', 'url': 'example.com'}]
Run Code Online (Sandbox Code Playgroud)