博客
关于我
字符串排序
阅读量:439 次
发布时间:2019-03-06

本文共 872 字,大约阅读时间需要 2 分钟。

为了解决问题,我们需要编写一个程序,按照特定规则排序输入字符串中的字符。规则包括:英文字母按顺序排列,同一英文字母的大小写保留输入顺序,非英文字母保持原位。

方法思路

  • 遍历字符串:记录每个字符及其位置。
  • 提取字母字符:将字母字符与其位置一起存储。
  • 自定义排序:根据规则对字母字符进行排序。比较时,先按小写字母顺序,相同字母按输入顺序排列。
  • 重建字符串:将排序后的字母字符放回原位置,非字母字符保持不变。
  • 解决代码

    s = input().strip()chars = list(s)letters = [(c, i) for i, c in enumerate(chars) if c.isalpha()]def compare(a, b):    if a[0].lower() == b[0].lower():        return a[1] - b[1]    return ord(a[0].lower()) - ord(b[0].lower())sorted_letters = sorted(letters, key=compare)result = []for i, c in enumerate(chars):    if c.isalpha():        result.append(sorted_letters[i][0])    else:        result.append(c)print(''.join(result))

    代码解释

  • 读取输入:使用input().strip()读取输入字符串并转换为列表。
  • 记录字符和位置:使用列表推导式遍历字符串,记录每个字符及其索引。
  • 提取字母字符:创建一个列表,存储每个字母字符及其索引。
  • 定义比较函数:比较函数compare首先比较小写字母,如果相同则比较原索引,确保按输入顺序排列。
  • 排序字母字符:使用sorted函数和自定义键进行排序。
  • 重建字符串:遍历原字符串,非字母字符保持原位,字母字符替换为排序后的结果。
  • 输出结果:将结果列表转换为字符串并输出。
  • 转载地址:http://mvjyz.baihongyu.com/

    你可能感兴趣的文章
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>
    Node-RED中使用json节点解析JSON数据
    查看>>