[英]Python : How to sort if the list contains the number and strings at the same time?
In my list, I had a mix of number and strings and the sort() doesn't not work on it, unfortunately.在我的列表中,我混合了数字和字符串,不幸的是 sort() 对它不起作用。 Any look around for this?
有没有看看这个?
Please help.请帮忙。
myList = ['rohit', 'mandiwal', 32, 7701]
TypeError: '<' not supported between instances of 'int' and 'str'
Use a sort key that creates a tuple that places strings or numbers first without having to compare them directly.
使用排序键创建一个先放置字符串或数字的元组,而不必直接比较它们。
Method: In each tuple, numbers have a 0 for the 1st element, strings have a 2.方法:在每个元组中,数字的第一个元素为 0,字符串的第一个元素为 2。
This keeps numbers and string from being compared and places numbers first.这可以防止比较数字和字符串,并将数字放在首位。 Can reverse this by making numbers 1 and strings 0.
可以通过使数字 1 和字符串 0 来反转这一点。
myList = ['rohit', 'mandiwal', 32, 7701, 3.5]
result = sorted(myList, key = lambda x: (isinstance(x, str), x))
print(result)
Simplified key with tip from @StefanPochmann带有@StefanPochmann 提示的简化密钥
Output输出
3.5, 32, 7701, 'mandiwal', 'rohit']
Convert your list into two sorted sub-lists, one containing numbers (ints and floats) and the other containing everything else.将您的列表转换为两个排序的子列表,一个包含数字(整数和浮点数),另一个包含其他所有内容。 Return the combined result.
返回组合结果。
myList = ['rohit', 'mandiwal', 32, 7701, 3.5]
result = (
sorted(n for n in myList if isinstance(n, (int, float)))
+ sorted(word for word in myList if not isinstance(word, (int, float)))
)
>>> result
[3.5, 32, 7701, 'mandiwal', 'rohit']
If you want the list to sorted alphabetically by treating each element as a string, then use sorted(myList, key=str)
.如果您希望通过将每个元素视为字符串来按字母顺序对列表进行排序,请使用
sorted(myList, key=str)
。 The basic idea is to use a key function to transform each list element into a value whose type supports comparison while the transformation enables the required sort ordering.基本思想是使用键函数将每个列表元素转换为一个类型支持比较的值,同时转换启用所需的排序顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.