按自定义顺序对字符串进行排序的 Python 程序

pythonserver side programmingprogramming更新于 2025/12/23 9:48:17

假设我们有一个字母数字字符串 s。我们必须根据以下条件对其进行排序

  • 所有排序后的小写字母将放在大写字母之前。

  • 所有排序后的大写字母将放在数字之前。

  • 所有排序后的奇数将放在排序后的偶数之前。

因此,如果输入为 s = "HeLlo1234",则输出为 eloHL1324

为了解决这个问题,我们将遵循以下步骤 −

  • 定义一个函数 f() 。这将需要 c
  • code := 0
  • 如果 c 是大写,则
    • code := 10^3
  • 否则,当 c 是数字时,则
    • code := 10^6
  • 如果 c 的 ASCII 为偶数,则
    • code := 10^9
  • 返回代码 + c 的 ASCII
  • 从主方法执行以下操作
  • l := s 的排序列表,并通过调用 f() 函数对 s 中的每个字符 c 进行排序
  • 连接 l 中的每个字符并返回

示例

让我们看看下面的实现以便更好地理解

def f(c):
   code = 0
   if c.isupper():
      code = 10 ** 3
   elif c.isdigit():
      code = 10 ** 6
      if ord(c) % 2 == 0:
         code = 10 ** 9
   return code + ord(c)

def solve(s):
   l = sorted(s, key=lambda c: f(c))
   return ''.join(l)

s = "HeLlo1234"
print(solve(s))

输入

"HeLlo1234"

输出

eloHL1324

相关文章


有用资源