gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:26:50 24 4
gpt4 key购买 nike

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

我有一堆 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com