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值进行排序。
相关推荐
pusheng20251 分钟前
普晟传感2026年新春年会总结与分析
前端·javascript·html
谢尔登2 分钟前
React19事件调度的设计思路
前端·javascript·react.js
不懒不懒5 分钟前
【HTML容器与表格布局实战指南】
java·开发语言
小W与影刀RPA5 分钟前
【影刀RPA】:智能过滤敏感词,高效输出表格
大数据·人工智能·python·低代码·自动化·rpa·影刀rpa
J_liaty6 分钟前
Java实现PDF添加水印的完整方案(支持灵活配置、平铺、多页策略)
java·开发语言·pdf
PPPPPaPeR.10 分钟前
从零实现一个简易 Shell:理解 Linux 进程与命令执行
linux·开发语言·c++
Yorlen_Zhang11 分钟前
python Tkinter Frame 深度解析与实战指南
开发语言·python
2401_8384725111 分钟前
Python多线程与多进程:如何选择?(GIL全局解释器锁详解)
jvm·数据库·python
lly20240613 分钟前
Eclipse 关闭项目详解
开发语言
LXS_35718 分钟前
C++常用容器(下)---stack、queue、list、set、map
开发语言·c++·学习方法·改行学it