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值进行排序。
相关推荐
前端 贾公子1 天前
v-if 与 v-for 的优先级对比
开发语言·前端·javascript
嗯嗯=1 天前
python学习篇
开发语言·python·学习
WoY20201 天前
opencv-python在ubuntu系统中缺少依赖
python·opencv·ubuntu
大游小游之老游1 天前
Python中如何实现一个程序运行时,调用另一文件中的函数
python
mantch1 天前
个人 LLM 接口服务项目:一个简洁的 AI 入口
人工智能·python·llm
不会c嘎嘎1 天前
QT中的常用控件 (二)
开发语言·qt
weixin_445054721 天前
力扣热题51
c++·python·算法·leetcode
小二·1 天前
Pinia 完全指南:用 TypeScript 构建可维护、可测试、可持久化的 Vue 3 状态管理
javascript·vue.js·typescript
是一个Bug1 天前
50道核心JVM面试题
java·开发语言·面试
bug总结1 天前
Vue3 实现后台管理系统跳转大屏自动登录功能
前端·javascript·vue.js