Python和JavaScript在字符串比较上的差异
目录
推荐超级课程:
在Python
和JavaScript
中,根据字符串末尾的字符进行排序时,Python
中只需将字符串传递给sorted
函数的key
参数即可,而在JavaScript
的sort
方法中,如果不进行特殊处理,默认只能进行数值比较而不是字符串比较,因此需要稍作技巧。
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值进行排序。