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值进行排序。
相关推荐
xywww1682 小时前
大模型 API 选型实战:GPT、Gemini、Claude 接入时该看哪些指标?
运维·服务器·人工智能·python·gpt·langchain
夜雪一千7 小时前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
能有时光7 小时前
PyTorch KernelAgent 源码解读 ---(4)--- ExtractorAgent
人工智能·pytorch·python
随风一样自由7 小时前
【前端独角兽】刚进入前端领域的前端开发用jQuery还是Vue3?
前端·javascript·vue3·jquery
_Jimmy_8 小时前
Python 协程库如何使用以及有哪些使用场景
python
aqi008 小时前
15天学会AI应用开发(十七)使用LangGraph实现会话记忆功能
人工智能·python·大模型·ai编程·ai应用
西门吹-禅8 小时前
java springboot N+1问题
java·开发语言·spring boot
YHHLAI8 小时前
[特殊字符] 面试中的 Promise —— 从入门到精通
前端·javascript·面试
第一程序员8 小时前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github
skywalk81638 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程