Python 3 Pandas: 自定义排序字符串列表

huangapple go评论70阅读模式
英文:

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']

huangapple
  • 本文由 发表于 2023年5月11日 03:34:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定