将字符串列表中的字符串按ascII从小到大排序
时间: 2023-10-02 10:07:38 浏览: 177
可以使用Python内置的sorted函数,指定key参数为ord函数即可按照ascII码从小到大排序。示例代码如下:
```python
string_list = ['apple', 'banana', 'cat', 'dog']
sorted_list = sorted(string_list, key=lambda s: ord(s[0]))
print(sorted_list)
```
输出:
```
['apple', 'banana', 'cat', 'dog']
```
相关问题
c语言 将字符串列表中的字符串按ascII从小到大排序
可以使用C语言中的qsort函数来进行排序,可以自定义比较函数来指定按照ascII码从小到大排序。示例代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 自定义比较函数
int cmp(const void *a, const void *b) {
return strcmp(*(char**)a, *(char**)b);
}
int main() {
char *string_list[] = {"apple", "banana", "cat", "dog"};
int n = sizeof(string_list) / sizeof(string_list[0]);
qsort(string_list, n, sizeof(char*), cmp);
for (int i = 0; i < n; i++) {
printf("%s ", string_list[i]);
}
printf("\n");
return 0;
}
```
输出:
```
apple banana cat dog
```
用python将多个字符串按ASCII 码从小到大排序
可以使用Python内置的`sorted`函数来实现字符串按ASCII码从小到大排序。具体实现方法如下:
```python
strings = ['apple', 'zebra', 'banana', 'orange']
sorted_strings = sorted(strings)
print(sorted_strings)
```
输出结果:
```
['apple', 'banana', 'orange', 'zebra']
```
在这个例子中,我们定义了一个字符串列表`strings`,并使用`sorted`函数将其按ASCII码从小到大排序,存储在变量`sorted_strings`中。最后,我们输出排好序的字符串列表`sorted_strings`。