sort函数主要分sort sorted。
a=[]
例如:
a.sort()
b=sorted(b)
sort用法:
1.sort处理数字
numbers = [3, 1, 4, 1, 5, 9, 2] numbers.sort() # 原地排序,修改原列表 print(numbers) # 输出: [1, 1, 2, 3, 4, 5, 9] # 降序排序 numbers.sort(reverse=True) print(numbers) # 输出: [9, 5, 4, 3, 2, 1, 1] 后面加条件:
单个条件: a.sort(key=lambda x:x)//按照X的大小排序 假设数字:884,98,57,51: 按照数字个位排序x[-1] a.sort(key=lambda x:x[-1]))
多个条件:
a.sort(key=lambda x:(x[-1],x))
这段代码的意思是先按照x的最后一位排,然后要是第一位相同按第二位。
2.sort处理字符:
在Python中,sort()
方法和sorted()
函数都可以用来对字符串列表进行排序,它们默认按照字典序
words = ['banana', 'apple', 'cherry', 'date'] words.sort() # 原地排序 print(words) # 输出: ['apple', 'banana', 'cherry', 'date'] # 使用sorted()函数 sorted_words = sorted(['banana', 'apple', 'cherry', 'date']) print(sorted_words) # 输出: ['apple', 'banana', 'cherry', 'date']
单条件:
words = ['banana', 'apple', 'cherry', 'date'] words.sort(key=len) # 按长度升序 print(words) # 输出: ['date', 'apple', 'banana', 'cherry'] # 按长度降序 words.sort(key=len, reverse=True) print(words) # 输出: ['banana', 'cherry', 'apple', 'date']
2.. 忽略大小写排序:
words = ['Apple', 'apple', 'Banana', 'banana']
words.sort(key=str.lower) # 转换为小写后比较
print(words) # 输出: ['Apple', 'apple', 'Banana', 'banana']
多条件排序:
# 先按长度排序,长度相同的按字母顺序排序
words = ['banana', 'apple', 'cherry', 'date', 'fig']
words.sort(key=lambda x: (len(x), x))
print(words) # 输出: ['fig', 'date', 'apple', 'banana', 'cherry']
自定义排序:
# 按字符串中特定字符的数量排序
words = ['banana', 'apple', 'cherry', 'date']
words.sort(key=lambda x: x.count('a')) # 按'a'的数量排序
print(words) # 输出: ['cherry', 'date', 'apple', 'banana']
以上就是我的蓝桥杯sort函数准备内容,希望大家携手共进,拿下果酱