python - 将字符串与数字进行比较,解码 radio 呼号

标签 python sorting

我有一种感觉,这个核心概念可能是一个重复的问题,但我找不到它。

我有一堆 radio 呼号,想从 here 中找到原产国.

我尝试进行基本比较以找到国家位置,但 Python 对数字和字符排序的方式与呼号的排序方式不同:

在 Python 中 "ZR1" < "ZRA" == True但这是 False在呼号约定中。

无论如何,我可以从 ... 7 < 8 < 9 < A < B … 更改 Python 的顺序吗?至 ... X < Y < Z < 0 < 1 < 2 …

最佳答案

您可以创建一个 dict以“正确”顺序将字符映射到它们的位置,然后比较位置列表:

import string
order = {e: i for i, e in enumerate(string.ascii_uppercase + string.digits)}
positions = lambda s: [order[c] for c in s]

def cmp_callsign(first, second):
    return cmp(positions(first), positions(second))  # (cmp removed in Python 3)

用法:

>>> positions("ZR1")
[25, 17, 27]
>>> cmp("ZR1", "ZRA")  # normal string comparison
-1
>>> cmp_callsign("ZR1", "ZRA")  # callsign comparison
1
>>> sorted(["AR1", "ZR1", "ZRA"], key=positions)
['AR1', 'ZRA', 'ZR1']

要使这种比较自动进行,您还可以创建一个 class Callsign并覆盖 __cmp____eq____lt__相应的方法:

class Callsign:
    def __init__(self, code):
        self.code = code
    def __lt__(self, other):
        return positions(self.code) < positions(other.code) 

a, b, c = Callsign("ZRA"), Callsign("ZR1"), Callsign("ZR9")
print(a < b < c)  # True
print(a < c < b)  # False

关于python - 将字符串与数字进行比较,解码 radio 呼号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187938/

相关文章:

c - 尝试使用字符串比较对链表进行排序时出错

javascript - 使用 jQuery 中 GET 请求的信息通过 Flask 显示转换后的结果

Python (Matplotlib) - 显示具有 x 和/或 y 偏移量的多个图形(图)(因此不会重叠)

Jenkins API 的 Python 日期时间问题

python flask : mimic werkzeug FileStorage object

python - 如何从 ipdb 中分配给 ipython 全局命名空间?

c++ - 快速排序实现,找不到错误

java - 使用数字字段对二维数组字符串进行排序

c++ - 实现堆排序

java - 使用快速排序按列对二维数组进行排序