1、下划线(_)的作用

  • python解析器最后一个表达式的值
  • 一个可以忽略的中间变量,filename, _ = 'example.txt'.split('.')
  • 格式化一个比较大的数据,amount = 1_000_000

2、zip用法

1
2
3
4
5
6
7
8
9
10
11
12
13
ids = [1, 2, 3]
names = ['Alice', 'Bob', 'Cathy']
grades = ['A', 'B', 'A+']

zipped = zip(ids, names, grades)
students = list(zipped) # [(1, 'Alice', 'A'), (2, 'Bob', 'B'), (3, 'Cathy', 'A+')]
unzipped = list(zip(*students))

keys = ['name', 'age', 'grade']
values = ['Alice', 25, 'A'] # [(1, 2, 3), ('Alice', 'Bob', 'Cathy'), ('A', 'B', 'A+')]

student_dict = dict(zip(keys, values))
print(student_dict) # {'name': 'Alice', 'age': 25, 'grade': 'A'}

3、sorted用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 根据字符串长度排序
words = ["apple", "banana", "pear", "cherry"]
sorted_words = sorted(words, key=len)

# 先根据第一位排序,再根据后面字符串排序
data = ['a5', 'a2', 'b1', 'b3', 'c2']
sorted_data = sorted(data, key=lambda x: (x[0], int(x[1:])))

# 根据第二位排序
tuples = [(1, 'c'), (2, 'a'), (1, 'b')]
sorted_tuples = sorted(tuples, key=lambda x: x[1])

# 根据字典的值进行排序
grades = {"Alice": 85, "Bob": 92, "Charlie": 88, "David": 76}
sorted_grades = sorted(grades.items(), key=lambda x: x[1])

# 忽略大小写进行字母排序
words = ["banana", "Apple", "cherry", "apple"]
sorted_words = sorted(words, key=lambda x: x.lower())

# 元组排序:按成绩降序排序,如果成绩相同则按名字升序排序
students = [("Alice", 85), ("Bob", 92), ("Charlie", 85), ("David", 76)]
sorted_students = sorted(students, key=lambda x: (-x[1], x[0]))

import functools

# 自定义比较函数
def compare(x, y):
if x[1] < y[1]:
return -1
elif x[1] > y[1]:
return 1
else:
return 0

# 使用比较函数进行排序
students = [("Alice", 85), ("Bob", 92), ("Charlie", 85), ("David", 76)]
sorted_students = sorted(students, key=functools.cmp_to_key(compare))

4、split的maxsplit参数

maxsplit(可选):指定最大分割次数。默认值是 -1,表示不限制分割次数。maxsplit 限制了分割次数,多余的部分会被合并成最后一个元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
text = "apple,banana,cherry,date"
result = text.split(",", 1) # 分割一次
print(result) # ['apple', 'banana,cherry,date']

result = text.split(",", 2) # 分割两次
print(result) # ['apple', 'banana', 'cherry,date']

result = text.split(",") # 分割所有的逗号
print(result) # ['apple', 'banana', 'cherry', 'date']

text = "apple,banana"
result = text.split(",", 5)
print(result) # ['apple', 'banana']

5、set用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
s = {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}

s.remove(2)
print(s) # Output: {1, 3, 4}

s.discard(10) # No error if 10 is not in set

a = {1, 2, 3}
b = {3, 4, 5}

# Union
print(a | b) # Output: {1, 2, 3, 4, 5}

# Intersection
print(a & b) # Output: {3}

# Difference
print(a - b) # Output: {1, 2}