英文:
Python 3 Pandas: Custom sorting a list of strings
问题
I can help you with the translation:
我需要对一组字符串进行排序,使得“非数字”值首先按字母顺序排序,然后是“数字”值按升序排序。
例如,假设列表是:
l = ['2.9', '-1', '0', 'ab2', 'xyz', 'ab']
我希望输出如下:
sorted_l = ['ab', 'ab2', 'xyz', '-1', '0', '2.9']
到目前为止,我只能在字符串都是“整数”时做到这一点:
import functools
l=['1','0','-1','2', '-9']
def compare(x, y):
return int(x) - int(y)
sorted_l = sorted(l, key = functools.cmp_to_key(compare))
如果不使用functools将会更理想。
谢谢。
英文:
I need to sort a list of strings such that "non-numeric" values are sorted alphabetically first, followed by "numeric" values, in ascending order.
For example, suppose the list is:
l = ['2.9', '-1', '0', 'ab2', 'xyz', 'ab']
I'd like the output to be:
sorted_l = ['ab', 'ab2', 'xyz', '-1', '0', '2.9']
So far, I can only do this if the strings are all "integers":
import functools
l=['1','0','-1','2', '-9']
def compare(x, y):
return int(x) - int(y)
sorted_l = sorted(l, key = functools.cmp_to_key(compare))
It'd be even more ideal if I can do it without using functools.
Thanks
答案1
得分: 3
A possible solution:
def is_numeric(s):
try:
float(s)
return True
except ValueError:
return False
l = ['2.9', '10', '0', 'ab2', 'xyz', 'ab']
l.sort(key=lambda x: (is_numeric(x), float(x) if is_numeric(x) else x))
Alternatively and more elegantly, we can follow @QuangHoang's suggestion:
def is_numeric(s):
try:
float(s)
return True, float(s)
except ValueError:
return False, s
l = ['2.9', '100', '0', 'ab2', 'xyz', 'ab']
l.sort(key=lambda x: is_numeric(x))
Output:
['ab', 'ab2', 'xyz', '-1', '0', '2.9']
英文:
A possible solution:
def is_numeric(s):
try:
float(s)
return True
except ValueError:
return False
l = ['2.9', '10', '0', 'ab2', 'xyz', 'ab']
l.sort(key=lambda x: (is_numeric(x), float(x) if is_numeric(x) else x))
Alternatively and more elegantly, we can follow @QuangHoang's suggestion:
def is_numeric(s):
try:
float(s)
return True, float(s)
except ValueError:
return False, s
l = ['2.9', '100', '0', 'ab2', 'xyz', 'ab']
l.sort(key=lambda x: is_numeric(x))
Output:
['ab', 'ab2', 'xyz', '-1', '0', '2.9']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论