1、(:=)的使用

Python 3.8 中引入,正式名称为赋值表达式,是一种将赋值与表达式相结合的新语法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 收集用户输入,直到输入空行
lines = []
while (line := input("Enter something (leave blank to quit): ")) != "":
lines.append(line)

# 筛选生成随机数
numbers = [n for _ in range(10) if (n := random.randint(1, 100)) > 50]
print(numbers)

# 赋值与if判断合成一行
a = [1, 2, 3]
if (n := len(a)) > 2:
print(f"The list is long enough ({n} elements).")

# 过滤并打印列表中的长单词
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
long_words = [word for word in words if (n := len(word)) > 5]
print(long_words) # ['banana', 'cherry', 'elderberry']

2、Counter的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from collections import Counter

c1 = Counter(a=4, b=2, c=0, d=-2)
c2 = Counter(a=1, b=2, c=3, d=4)

# Addition
print(c1 + c2) # Output: Counter({'a': 5, 'c': 3, 'b': 4, 'd': 2})

# Subtraction
print(c1 - c2) # Output: Counter({'a': 3})

# Intersection
print(c1 & c2) # Output: Counter({'a': 1, 'b': 2})

# Union
print(c1 | c2) # Output: Counter({'a': 4, 'c': 3, 'b': 2, 'd': 4})
1
2
3
4
5
6
7
8
9
10
11
12
13
from collections import Counter
import re

# Sample text
text = "Python is great. Python is dynamic. Python is popular."

# Tokenize the text (convert to lowercase to count all variations of the word)
words = re.findall(r'\b\w+\b', text.lower())

# Create a Counter object
word_count = Counter(words)

print(word_count)

3、(*) 号在解包中的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
# 忽略中间部分
first, *_, last = [1, 2, 3, 4, 5]
print(first, last) # Output: 1 5

# 表示0到多个
first, *rest = [1, 2, 3, 4, 5]
print(first) # Output: 1
print(rest) # Output: [2, 3, 4, 5] 剩余内容

# 表示0到多个
*rest, last = [1, 2, 3, 4, 5]
print(rest) # Output: [1, 2, 3, 4]
print(last) # Output: 5

4、Max、Min的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
names: list[str] = ['John', 'Doe', 'Jack', 'Bob', 'Smith']

for name in names:
print(name, name.count('a'), sep=': ')
# 输出
# John: 0
# Doe: 0
# Jack: 1
# Bob: 0
# Smith: 0

print('Max: ', max(names, key=lambda x: x.count('a'))) # 输出 Max: Jack
print('Min: ', min(names, key=lambda x: x.count('a'))) # 输出 Min: John

print('Max: ', max(names, key=len)) # 输出 Max: Smith
print('Min: ', min(names, key=len)) # 输出 Min: Doe

5、round四舍五入

1
2
3
4
number: float = 1314521.56789
print(round(number, 2)) # 1314521.57
print(round(number, -1)) # 1314520.0
print(round(number, -3)) # 1315000.0