将列表内的字符串按照长度排序,若字符串长度相同,则把相同长度的字符串按照的固有排序准则降序排序
时间: 2024-05-10 15:21:20 浏览: 125
可以使用sorted函数,其中的key参数可以指定排序方式。首先按照字符串长度排序,如果长度相同再按照字符串本身的降序排序。
代码如下:
```python
lst = ['apple', 'banana', 'pear', 'orange', 'grape', 'kiwi']
sorted_lst = sorted(lst, key=lambda x: (len(x), x), reverse=True)
print(sorted_lst)
```
输出结果为:
```
['banana', 'orange', 'grape', 'apple', 'pear', 'kiwi']
```
相关问题
数字串请按照数字的大小由大到小进行排序,非数字串请按照长度有短到长进行排 序,若长度相等,则按照字符串的固有排序准则降序排序,并进行输出,请编写函 数进行输出操作;
假设输入的字符串列表为str_list,则可以使用以下函数进行排序和输出操作:
```python
def sort_and_print(str_list):
num_list = []
str_len_dict = {}
for s in str_list:
if s.isdigit():
num_list.append(int(s))
else:
if len(s) not in str_len_dict:
str_len_dict[len(s)] = []
str_len_dict[len(s)].append(s)
num_list.sort(reverse=True)
for l in sorted(str_len_dict.keys()):
str_list = str_len_dict[l]
str_list.sort(reverse=True)
for s in str_list:
print(s)
for n in num_list:
print(n)
```
该函数首先将数字串和非数字串分别存储到两个列表中,然后将数字串进行排序,按照从大到小的顺序输出。接着,将非数字串按照长度存储到一个字典中,每个长度对应一个字符串列表。对于每个长度,将字符串列表按照字符串的固有排序准则降序排序,然后输出。最后,输出完所有非数字串后,再输出已经排好序的数字串。
阅读全文
相关推荐
















