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值进行排序。
相关推荐
嘻嘻哈哈OK啦1 分钟前
day46打卡
python
IGP94 分钟前
20250606-C#知识:委托和事件
开发语言·c#
木头左6 分钟前
Docker容器化技术概述与实践
python
江城开朗的豌豆10 分钟前
JavaScript篇:前端定时器黑科技:不用setInterval照样玩转循环任务
前端·javascript·面试
hjyowl14 分钟前
题解:AT_abc407_c [ABC407C] Security 2
c语言·开发语言·算法
唐墨12315 分钟前
android与Qt类比
android·开发语言·qt
坚持就完事了26 分钟前
大二下期末
python·numpy·pandas
蹦蹦跳跳真可爱58928 分钟前
Python----目标检测(使用YOLO 模型进行线程安全推理和流媒体源)
人工智能·python·yolo·目标检测·目标跟踪
江城开朗的豌豆38 分钟前
JavaScript篇:自定义事件:让你的代码学会'打小报告'
前端·javascript·面试
Code_流苏43 分钟前
C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)
开发语言·c++·stl容器·课设·期末大作业·日历程序·面向对象设计