十個 Python 編程中的聰明小把戲
1. 把戲1:列表推導(dǎo)式
列表推導(dǎo)式是一種簡潔地創(chuàng)建新列表的方法。它可以讓你一行代碼搞定原本需要多行才能完成的任務(wù)。
示例1:
假設(shè)我們需要創(chuàng)建一個列表,包含0到9這10個數(shù)字的平方。
# 普通方法
squares = []
for i in range(10):
squares.append(i ** 2)
print(squares)
# 列表推導(dǎo)式
squares = [i ** 2 for i in range(10)]
print(squares)
輸出:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
解釋: 列表推導(dǎo)式的語法是 [expression for item in iterable]。這里 expression 是 i ** 2,item 是 i,iterable 是 range(10)。
2. 把戲2:字典推導(dǎo)式
字典推導(dǎo)式類似于列表推導(dǎo)式,但用于創(chuàng)建字典。
示例2:
創(chuàng)建一個字典,鍵為0到9,值為鍵的平方。
# 普通方法
squares_dict = {}
for i in range(10):
squares_dict[i] = i ** 2
print(squares_dict)
# 字典推導(dǎo)式
squares_dict = {i: i ** 2 for i in range(10)}
print(squares_dict)
輸出:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
解釋: 字典推導(dǎo)式的語法是 {key: value for item in iterable}。這里 key 是 i,value 是 i ** 2,iterable 是 range(10)。
3. 把戲3:條件表達式(三元運算符)
Python中可以用一行代碼實現(xiàn)條件判斷。
示例3:
根據(jù)年齡判斷是否成年。
age = 25
# 普通方法
if age >= 18:
result = "成年"
else:
result = "未成年"
print(result)
# 條件表達式
result = "成年" if age >=
輸出:
成年
解釋: 條件表達式的語法是 value_if_true if condition else value_if_false。這里 condition 是 age >= 18,value_if_true 是 "成年",value_if_false 是 "未成年"。
4. 把戲4:解包操作
解包可以方便地將列表或元組中的元素分配給多個變量。
示例4:
交換兩個變量的值。
a = 10
b = 20
# 普通方法
temp = a
a = b
b = temp
print(a, b)
# 解包操作
a, b = b, a
print(a, b)
輸出:
20 10
解釋: 解包操作的語法是 var1, var2 = value1, value2。這里 var1 和 var2 分別是 a 和 b,value1 和 value2 分別是 b 和 a。
5. 把戲5:使用enumerate簡化循環(huán)
enumerate函數(shù)可以在遍歷列表時同時獲取索引和值。
示例5:
打印列表中每個元素及其索引。
fruits = ["apple", "banana", "cherry"]
# 普通方法
index = 0
for fruit in fruits:
print(f"索引 {index}: {fruit}")
index += 1
# 使用enumerate
for index, fruit in enumerate(fruits):
print(f"索引 {index}: {fruit}")
輸出:
索引 0: apple
索引 1: banana
索引 2: cherry
解釋: enumerate的語法是 enumerate(iterable, start=0)。這里 iterable 是 fruits,默認(rèn)的起始索引是0。enumerate返回一個迭代器,每次迭代產(chǎn)生一個元組 (index, value)。
6. 把戲6:使用zip合并多個列表
zip函數(shù)可以將多個列表中的對應(yīng)元素打包成元組。
示例6:
合并姓名和年齡列表。
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
# 普通方法
for i in range(len(names)):
print(f"{names[i]} 的年齡是 {ages[i]}")
# 使用zip
for name, age in zip(names, ages):
print(f"{name} 的年齡是 {age}")
輸出:
Alice 的年齡是 25
Bob 的年齡是 30
Charlie 的年齡是 35
解釋: zip的語法是 zip(*iterables)。這里 *iterables 是 names 和 ages。zip返回一個迭代器,每次迭代產(chǎn)生一個元組 (name, age)。
7. 把戲7:使用any和all檢查條件
any和all函數(shù)可以快速檢查列表中的所有元素是否滿足某個條件。
示例7:
檢查列表中是否有偶數(shù)。
numbers = [1, 2, 3, 4, 5]
# 使用any
has_even = any(number % 2 == 0 for number in numbers)
print(has_even)
# 使用all
all_odd = all(number % 2 != 0 for number in numbers)
print(all_odd)
輸出:
True
False
解釋:
- any的語法是 any(iterable)。如果 iterable 中有任何一個元素為 True,則返回 True。
- all的語法是 all(iterable)。如果 iterable 中的所有元素都為 True,則返回 True。
8. 把戲8:使用列表切片反轉(zhuǎn)列表
列表切片可以輕松地反轉(zhuǎn)列表。
示例8:
反轉(zhuǎn)一個列表。
numbers = [1, 2, 3, 4, 5]
# 普通方法
reversed_numbers = []
for i in range(len(numbers) - 1, -1, -1):
reversed_numbers.append(numbers[i])
print(reversed_numbers)
# 使用切片
reversed_numbers = numbers[::-1]
print(reversed_numbers)
輸出:
[5, 4, 3, 2, 1]
解釋: 列表切片的語法是 list[start:stop:step]。這里 start 是默認(rèn)值 0,stop 是默認(rèn)值 len(numbers),step 是 -1。
9. 把戲9:使用sorted排序列表
sorted函數(shù)可以輕松地對列表進行排序。
示例9:
對字符串列表按長度排序。
words = ["apple", "banana", "cherry", "date"]
# 按字母順序排序
sorted_words = sorted(words)
print(sorted_words)
# 按長度排序
sorted_words = sorted(words, key=len)
print(sorted_words)
輸出:
['apple', 'banana', 'cherry', 'date']
['date', 'apple', 'banana', 'cherry']
解釋: sorted的語法是 sorted(iterable, key=None, reverse=False)。這里 iterable 是 words,key 是 len 函數(shù),表示按長度排序。
10. 把戲10:使用生成器表達式節(jié)省內(nèi)存
生成器表達式可以像列表推導(dǎo)式一樣生成數(shù)據(jù),但不會一次性加載所有數(shù)據(jù)到內(nèi)存。
示例10:
計算0到9這10個數(shù)字的平方。
# 列表推導(dǎo)式
squares_list = [i ** 2 for i in range(10)]
print(squares_list)
# 生成器表達式
squares_gen = (i ** 2 for i in range(10))
print(list(squares_gen))
輸出:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
解釋: 生成器表達式的語法是 (expression for item in iterable)。這里 expression 是 i ** 2,item 是 i,iterable 是 range(10)。生成器表達式返回一個生成器對象,可以逐個生成數(shù)據(jù),節(jié)省內(nèi)存。
11. 實戰(zhàn)案例:統(tǒng)計文本文件中的單詞數(shù)量
假設(shè)有一個文本文件 text.txt,內(nèi)容如下:
Hello world
This is a test file
Python is awesome
我們可以編寫一個程序來統(tǒng)計文件中每個單詞出現(xiàn)的次數(shù)。
代碼示例:
from collections import Counter
import re
def count_words(filename):
# 打開文件并讀取內(nèi)容
with open(filename, "r") as file:
text = file.read()
# 使用正則表達式提取單詞
words = re.findall(r'\w+', text.lower())
# 統(tǒng)計單詞數(shù)量
word_count = Counter(words)
return word_count
# 調(diào)用函數(shù)
filename = "text.txt"
word_count = count_words(filename)
# 輸出結(jié)果
for word, count in word_count.items():
print(f"{word}: {count}")
輸出:
hello: 1
world: 1
this: 1
is: 2
a: 1
test: 1
file: 1
python: 1
awesome: 1
解釋:
- 使用 with open(filename, "r") as file: 打開文件并讀取內(nèi)容。
- 使用正則表達式 re.findall(r'\w+', text.lower()) 提取所有單詞,并轉(zhuǎn)換為小寫。
- 使用 Counter 統(tǒng)計每個單詞出現(xiàn)的次數(shù)。
- 輸出結(jié)果。