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值进行排序。
相关推荐
jyOverQ11 分钟前
LangGraph 流式执行详解:stream、astream 与 stream_mode 怎么选?
python·langchain
法哥201222 分钟前
用 C++ 控制 CMW100,到底在干什么?
开发语言·c++
闲猫27 分钟前
LangGraph / Capabilities / Stores
python·agent·langgraph
QH1392923188030 分钟前
NVIDIA H200 H300服务器
运维·服务器·开发语言·网络·信息与通信
pjj1985438 分钟前
机器学习-NumPy2
人工智能·python·机器学习
OPEN-F1 小时前
Python进阶教程:单元测试与代码质量
开发语言·python·单元测试
阿里嘎多学长1 小时前
2026-08-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
其实防守也摸鱼1 小时前
Codex破局:前端组件秒级生成的技术文章大纲
开发语言·前端·人工智能·学习·安全·web安全
Logintern091 小时前
装饰器和洋葱模式的区分
开发语言·python·架构
冻柠檬飞冰走茶1 小时前
《数据结构实验指导-C++语言版》 在顺序表 list 中查找元素 x
开发语言·数据结构·c++·算法·list