简体   繁体   English

Python - 如何对字母和数值列表进行排序?

[英]Python - How to sort a list of alpha and numeric values?

Is there a fast way to sort this list :有没有一种快速的方法来排序这个列表:

list = ['J', 'E', 3, 7, 0]

in order to get this one (numeric first, and then alpha) in python?为了在python中获得这个(先是数字,然后是alpha)? :

list = [0, 3, 7, 'E', 'J']

Since you're dealing with numbers (that, in this case, are <10) and strings, you can simplify your key and remove the lambda :由于您正在处理数字(在本例中为 <10)和字符串,因此您可以简化您的键并删除lambda

>>> sorted(lst, key=str)
[0, 3, 7, 'E', 'J']

Or, even better, use list.sort for an in-place sorting.或者,更好的是,使用list.sort进行就地排序。

>>> lst.sort(key=str)
>>> lst
[0, 3, 7, 'E', 'J']

Each item will be sorted based on the ASCII value of the str -ified value.每个项目将根据str化值的 ASCII 值进行排序。

Note that, if you're dealing with numbers >=10 (highly likely), then this solution will end up sorting the numbers lexicographically.请注意,如果您处理的数字 >=10(很有可能),那么此解决方案最终会按字典顺序对数字进行排序。 To get around that, you will end up needing the lambda.为了解决这个问题,您最终将需要 lambda。

>>> lst.sort(key=lambda x: (isinstance(x, str), x)))

Which is @jpp's solution.这是@jpp 的解决方案。

You can sort with a (Boolean, value) tuple:您可以使用 (Boolean, value) 元组进行排序:

L = ['J', 'E', 3, 7, 0]

res = sorted(L, key=lambda x: (isinstance(x, str), x))

# [0, 3, 7, 'E', 'J']

If you will use list.sort() on you list, you will get如果你在你的列表中使用list.sort() ,你会得到

TypeError: '<' not supported between instances of 'int' and 'str'

You have to convert all items in list into string type.您必须将列表中的所有项目转换为字符串类型。

[str(i) for i in list]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM