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值进行排序。
相关推荐
m0_73494979几秒前
CSS 背景图片无法加载的常见原因与正确写法详解
jvm·数据库·python
2301_815279522 分钟前
mysql如何使用yum安装mysql_配置官方yum源与自动安装
jvm·数据库·python
qq_12084093714 分钟前
Three.js 工程向:Frustum Culling 与场景分块优化实战
前端·javascript
大肥羊学校懒羊羊4 分钟前
质因数个数问题:高效分解算法详解
开发语言·c++·算法
weixin_458580125 分钟前
MySQL跨版本迁移数据格式不兼容_使用mysqldump全量导出导入
jvm·数据库·python
新缸中之脑6 分钟前
用Claude for Word审查法律合同
开发语言·c#·word
沐知全栈开发8 分钟前
SQLite 子查询
开发语言
Greyson19 分钟前
SQL触发器在导入大文件时如何跳过_使用禁用触发器语句导入
jvm·数据库·python
Full Stack Developme11 分钟前
Hutool JSON 操作教程
windows·python·json
2401_8877245012 分钟前
Redis怎样统计独立访客UV_基于Set的SADD指令天然去重特性
jvm·数据库·python