[英]How to sort a list that contains both numbers and letters?
I am trying to join and sort some list that contains numbers and letters我正在尝试加入并排序一些包含数字和字母的列表
for example:例如:
l1 = ['AF', '0.167']
l2 = ['AF', '1']
l3 = ['AC', '1']
l4 = ['AC', '6']
if I join l1 and l2 together, l3 and l4 together and reverse them (wish letters come first), I will get two different results.如果我将 l1 和 l2 连接在一起,将 l3 和 l4 连接在一起并将它们反转(希望字母在前),我将得到两个不同的结果。
['0.167', 'AF', '1']
['1', 'AF', '0.167']
--------------------
['6', '1', 'AC']
['AC', '1', '6']
why the second one can sort properly , but the first one only switch the positions of numbers.为什么第二个可以正常排序,而第一个只能切换数字的位置。
if I expect to get : new1 =['AF', '0.167, 1'] , new2 = ['AC', '1, 6']
How can I change the code.如果我希望得到:
new1 =['AF', '0.167, 1'] , new2 = ['AC', '1, 6']
如何更改代码。
The code is here:代码在这里:
l1 = ['AF', '0.167']
l2 = ['AF', '1']
l3 = ['AC', '1']
l4 = ['AC', '6']
new1 = l1 + l2
new1 = list(set(new1))
new2 = l3 + l4
new2 = list(set(new2))
list(reversed(new1))
list(reversed(new2))
print( new1 )
print(list(reversed(new1)) )
print('--------------------')
print( new2 )
print(list(reversed(new2)) )
There are a couple of things that need to be clarified:有几件事需要澄清:
list(set(thing))
will give you a list with "random" orderlist(set(thing))
会给你一个“随机”顺序的列表reversed()
does exactly what it sounds like, it enables you to iterate in reversed order, it doesn't do any sorting. reversed()
完全符合它的要求,它使您能够以相反的顺序进行迭代,它不进行任何排序。 If you want sorting, use sorted()
sorted()
If I understand correctly, you want your strings to come first, followed by the sorted "numbers" (which are actually strings containing representation of numbers).如果我理解正确,您希望您的字符串首先出现,然后是排序的“数字”(实际上是包含数字表示的字符串)。
To do this, you'll need an appropriate sorting function.为此,您需要一个适当的排序功能。 Something like the following should work:
像下面这样的东西应该工作:
>>> test1 = ['0.167', 'AF', '1']
>>> test2 = ['6', '1', 'AC']
>>> sort_key = lambda s: float('-inf') if s.isalpha() else float(s)
>>> sorted(test1, key=sort_key)
['AF', '0.167', '1']
>>> sorted(test2, key=sort_key)
['AC', '1', '6']
Depending on your data, having dict with strings as keys and a list of numbers as value might make more sense for storing it, and would be simpler to sort.根据您的数据,将 dict 与字符串作为键并将数字列表作为值可能更适合存储它,并且更易于排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.