Python和JavaScript在字符串比较上的差异

Python和JavaScript在字符串比较上的差异

目录

推荐超级课程:

PythonJavaScript中,根据字符串末尾的字符进行排序时,Python中只需将字符串传递给sorted函数的key参数即可,而在JavaScriptsort方法中,如果不进行特殊处理,默认只能进行数值比较而不是字符串比较,因此需要稍作技巧。

Python

python 复制代码
def sort_by_last_char(arr):
    return sorted(arr, key=lambda x: x[-1])
arr = ['apple', 'banana', 'cherry', 'date']
sorted_arr = sort_by_last_char(arr)
print(sorted_arr)

!

  • sorted函数会根据指定的键(key)对数组进行排序。
  • 这里使用key=lambda x: x[-1],即以每个字符串的最后一个字符为基准进行排序。

JavaScript

使用localeCompare的方法

javascript 复制代码
const sortByLastCharLocaleCompare = arr => arr.sort((a, b) => a.charAt(a.length - 1).localeCompare(b.charAt(b.length - 1))); //也可以使用slice方法
const arr1 = ['apple', 'banana', 'cherry', 'date'];
const sortedArr1 = sortByLastCharLocaleCompare(arr1);
console.log(sortedArr1);

!

  • sort方法会根据指定的比较函数对数组进行排序。
  • localeCompare会根据本地设置比较字符串,并据此进行排序。

使用charCodeAt的方法

javascript 复制代码
const sortByLastCharCharCodeAt = arr => arr.sort((a, b) => a.charCodeAt(a.length - 1) - b.charCodeAt(b.length - 1));
const arr2 = ['apple', 'banana', 'cherry', 'date'];
const sortedArr2 = sortByLastCharCharCodeAt(arr2);
console.log(sortedArr2);

!

  • charCodeAt方法返回指定位置字符的Unicode编码。
  • sort方法内部,根据字符的Unicode值进行排序。
相关推荐
c++之路9 分钟前
C++ 多线程
开发语言·c++
CHANG_THE_WORLD14 分钟前
<Fluent Python > Unicode 文本与字节
开发语言·python
测试员周周15 分钟前
【AI测试系统】第1篇:LangGraph 实战:用 State Graph 搭建 AI测试流水线(4 步编排 + RAG 增强 + 完整代码)
linux·windows·python·功能测试·microsoft·单元测试·多轮对话
AI人工智能+电脑小能手19 分钟前
【大白话说Java面试题】【Java基础篇】第20题:HashMap在计算index的时候,为什么要对数组长度做减1操作
java·开发语言·数据结构·后端·面试·哈希算法·hash-index
凯瑟琳.奥古斯特20 分钟前
Bootstrap快速上手指南
开发语言·前端·css·bootstrap·html
噜噜噜阿鲁~20 分钟前
python学习笔记 | 8.2、函数式编程-返回函数
笔记·python·学习
恶猫29 分钟前
网页自动化模拟操作时,模拟真实按键触发事件【终级方案】
前端·javascript·自动化·vue·网页模拟
我就是妖怪32 分钟前
Kimi K2.6 智能效果实测与能力全景展示
开发语言
中二痞35 分钟前
下载Python 版本,环境变量变更以及PyCharm更换python版本
开发语言·python·pycharm
故事和你9138 分钟前
洛谷-算法2-3-分治与倍增5
开发语言·数据结构·c++·算法·动态规划·图论