Python基礎(chǔ)指南之列表推導(dǎo)式的入門與靈活運(yùn)用
一、開篇:讓循環(huán)消失的魔法
前面幾篇文章我們學(xué)完了列表的所有基礎(chǔ)操作。今天我們要學(xué)的是Python中最有"Python味"的特性之一——列表推導(dǎo)式(List Comprehension)。
如果你問我,什么代碼一看就是"Python新手寫的"?我的回答往往是:用五行的 for 循環(huán)創(chuàng)建列表,而明明可以一行推導(dǎo)式搞定。列表推導(dǎo)式不僅是語法糖——它更短、更快、更易讀,是Pythonic代碼的標(biāo)志之一。
很多初學(xué)者覺得推導(dǎo)式"有點(diǎn)難讀",于是回避不用。但一旦你掌握了它,你會(huì)發(fā)現(xiàn)它不僅不難讀,反而比等價(jià)的for循環(huán)更清晰地表達(dá)了意圖——“我在創(chuàng)建一個(gè)新列表,規(guī)則是xxx”。今天這篇文章,我會(huì)帶你從最簡單的推導(dǎo)式入門,一路到嵌套、條件、多循環(huán)的高級(jí)應(yīng)用。
二、列表推導(dǎo)式的基本語法
2.1 從for循環(huán)到推導(dǎo)式
# 傳統(tǒng)for循環(huán)——?jiǎng)?chuàng)建一個(gè)平方數(shù)列表
squares = []
for x in range(10):
squares.append(x ** 2)
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 列表推導(dǎo)式——同樣的事情,一行搞定
squares = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 語法結(jié)構(gòu):[表達(dá)式 for 變量 in 可迭代對(duì)象]
# 1. 表達(dá)式:對(duì)每個(gè)元素做什么操作
# 2. for 變量 in 可迭代對(duì)象:遍歷的數(shù)據(jù)源
2.2 最簡單的推導(dǎo)式
# 收集原始數(shù)據(jù)(不做變換) nums = [x for x in range(10)] print(nums) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 等同于 list(range(10)),但展示了推導(dǎo)式的基本形式 # 對(duì)每個(gè)元素應(yīng)用函數(shù) words = ['hello', 'world', 'python'] upper_words = [w.upper() for w in words] print(upper_words) # ['HELLO', 'WORLD', 'PYTHON'] # 對(duì)每個(gè)元素做運(yùn)算 prices = [100, 200, 300, 400] with_tax = [p * 1.1 for p in prices] print(with_tax) # [110.0, 220.0, 330.0, 440.0] # 從字符串中提取 text = 'Python編程' chars = [c for c in text] print(chars) # ['P', 'y', 't', 'h', 'o', 'n', '編', '程'] # 調(diào)用函數(shù) import math roots = [math.sqrt(x) for x in range(1, 6)] print(roots) # [1.0, 1.414..., 1.732..., 2.0, 2.236...] # 保留兩位小數(shù) roots = [round(math.sqrt(x), 2) for x in range(1, 6)] print(roots) # [1.0, 1.41, 1.73, 2.0, 2.24]
三、帶條件的推導(dǎo)式
3.1 過濾條件(if在for后面)
# 只保留偶數(shù) numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = [x for x in numbers if x % 2 == 0] print(evens) # [2, 4, 6, 8, 10] # 只保留長度大于3的單詞 words = ['a', 'ab', 'abc', 'abcd', 'abcde'] long_words = [w for w in words if len(w) > 3] print(long_words) # ['abcd', 'abcde'] # 多個(gè)if條件——相當(dāng)于and # 保留能被2整除且能被3整除的數(shù)(即能被6整除) result = [x for x in range(50) if x % 2 == 0 if x % 3 == 0] print(result) # [0, 6, 12, 18, 24, 30, 36, 42, 48] # 等價(jià)于 result = [x for x in range(50) if x % 2 == 0 and x % 3 == 0] # 過濾出非空非空白字符串 data = ['hello', '', ' ', 'world', '\t', 'python'] valid = [s for s in data if s.strip()] print(valid) # ['hello', 'world', 'python']
3.2 條件表達(dá)式(if-else在for前面)
# if-else在for前面:對(duì)每個(gè)元素做"轉(zhuǎn)換"(二選一)
# 不能被過濾掉,長度不變!
# 偶數(shù)為本身,奇數(shù)為0
nums = [1, 2, 3, 4, 5]
result = [x if x % 2 == 0 else 0 for x in nums]
print(result) # [0, 2, 0, 4, 0]
# 大于等于60為'及格',否則為'不及格'
scores = [85, 45, 92, 58, 78, 30]
grades = ['及格' if s >= 60 else '不及格' for s in scores]
print(grades) # ['及格', '不及格', '及格', '不及格', '及格', '不及格']
# 混合使用:過濾 + 轉(zhuǎn)換
# 只保留及格的分?jǐn)?shù),并標(biāo)注等級(jí)
scores = [85, 45, 92, 58, 78, 30]
levels = [
'優(yōu)秀' if s >= 90 else '良好' if s >= 80 else '中等' if s >= 70 else '及格'
for s in scores if s >= 60
]
print(levels) # ['良好', '優(yōu)秀', '中等']
# 關(guān)鍵區(qū)分:
# [表達(dá)式 for x in lst if 條件] → if在for后面=過濾,元素?cái)?shù)量可能變少
# [A if 條件 else B for x in lst] → if-else在for前面=轉(zhuǎn)換,元素?cái)?shù)量不變
3.3 過濾+轉(zhuǎn)換的組合
# 完整形式:[轉(zhuǎn)換表達(dá)式 for x in iterable if 過濾條件]
# 場景:獲取所有及格分?jǐn)?shù)的平方根
scores = [85, 45, 92, 58, 78, 30, 66]
import math
passing_roots = [round(math.sqrt(s), 2) for s in scores if s >= 60]
print(passing_roots) # [9.22, 9.59, 8.83, 8.12]
# 場景:獲取文件列表中所有.txt文件的大寫文件名
files = ['readme.txt', 'main.py', 'config.txt', 'test.py', 'data.csv']
txt_upper = [f.upper() for f in files if f.endswith('.txt')]
print(txt_upper) # ['README.TXT', 'CONFIG.TXT']
# 場景:找出100以內(nèi)所有素?cái)?shù)
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
primes = [x for x in range(2, 100) if is_prime(x)]
print(primes)
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
四、嵌套循環(huán)的推導(dǎo)式
4.1 雙層循環(huán)
# 傳統(tǒng)for循環(huán)——笛卡爾積
pairs = []
for x in range(3):
for y in range(2):
pairs.append((x, y))
print(pairs)
# [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
# 推導(dǎo)式——順序和for循環(huán)一致
pairs = [(x, y) for x in range(3) for y in range(2)]
print(pairs)
# [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
# 核心規(guī)則:推導(dǎo)式中for的順序 = 嵌套for循環(huán)的順序
# 外層for在前,內(nèi)層for在后
# 組合顏色和尺寸
colors = ['紅色', '藍(lán)色']
sizes = ['S', 'M', 'L']
products = [(c, s) for c in colors for s in sizes]
print(products)
# [('紅色', 'S'), ('紅色', 'M'), ('紅色', 'L'),
# ('藍(lán)色', 'S'), ('藍(lán)色', 'M'), ('藍(lán)色', 'L')]
# 配合條件過濾
# 排除同色同尺寸(當(dāng)顏色=紅色且尺寸=L時(shí)排除)
filtered = [(c, s) for c in colors for s in sizes
if not (c == '紅色' and s == 'L')]
print(filtered)
# [('紅色', 'S'), ('紅色', 'M'), ('藍(lán)色', 'S'), ('藍(lán)色', 'M'), ('藍(lán)色', 'L')]
4.2 扁平化嵌套列表
# 二維列表→一維列表
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
# 傳統(tǒng)方式
flat = []
for row in matrix:
for item in row:
flat.append(item)
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 推導(dǎo)式
flat = [item for row in matrix for item in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 只保留偶數(shù)
flat_evens = [item for row in matrix for item in row if item % 2 == 0]
print(flat_evens) # [2, 4, 6, 8]
# 三維→一維
cube = [
[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
]
flat_cube = [item for plane in cube for row in plane for item in row]
print(flat_cube) # [1, 2, 3, 4, 5, 6, 7, 8]
4.3 矩陣操作
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 轉(zhuǎn)置矩陣
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# 等價(jià)于 zip(*matrix)
print([list(col) for col in zip(*matrix)]) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# 生成乘法表
mult_table = [[i * j for j in range(1, 10)] for i in range(1, 10)]
for row in mult_table:
print(' '.join(f'{n:2d}' for n in row))
# 生成單位矩陣
n = 5
identity = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
for row in identity:
print(row)
# [1, 0, 0, 0, 0]
# [0, 1, 0, 0, 0]
# ...
五、推導(dǎo)式中的表達(dá)式技巧
5.1 復(fù)雜表達(dá)式
# 表達(dá)式可以是任意合法的Python表達(dá)式
# 調(diào)用方法
words = ['hello', 'world', 'python']
caps = [w.capitalize() for w in words]
print(caps) # ['Hello', 'World', 'Python']
# 字符串格式化
names = ['小明', '小紅', '小剛']
greetings = [f'你好,{name}!' for name in names]
print(greetings) # ['你好,小明!', '你好,小紅!', '你好,小剛!']
# 三元表達(dá)式
nums = [1, 2, 3, 4, 5]
labels = ['奇數(shù)' if x % 2 else '偶數(shù)' for x in nums]
print(labels) # ['奇數(shù)', '偶數(shù)', '奇數(shù)', '偶數(shù)', '奇數(shù)']
# 元組構(gòu)造
data = [1, 2, 3, 4, 5]
indexed = [(i, x) for i, x in enumerate(data)]
print(indexed) # [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
# 多重賦值的使用
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
swapped = [(b, a) for a, b in pairs]
print(swapped) # [('a', 1), ('b', 2), ('c', 3)]
# zip的組合
names = ['小明', '小紅', '小剛']
ages = [25, 23, 26]
profiles = [f'{n}今年{a}歲' for n, a in zip(names, ages)]
print(profiles) # ['小明今年25歲', '小紅今年23歲', '小剛今年26歲']
5.2 調(diào)用函數(shù)
# 表達(dá)式可以調(diào)用任何函數(shù)
import hashlib
passwords = ['hello', 'world', 'python123']
hashed = [hashlib.sha256(p.encode()).hexdigest()[:8] for p in passwords]
print(hashed)
# 調(diào)用自定義函數(shù)
def grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
scores = [95, 82, 73, 45, 88, 91]
grades = [grade(s) for s in scores]
print(grades) # ['A', 'B', 'C', 'F', 'B', 'A']
# 使用內(nèi)置函數(shù)
names = [' Alice ', 'BOB ', ' Charlie']
cleaned = [n.strip().capitalize() for n in names]
print(cleaned) # ['Alice', 'Bob', 'Charlie']
5.3 列表推導(dǎo)式中的海象運(yùn)算符(Python 3.8+)
# 使用 := 避免重復(fù)計(jì)算
import math
# 傳統(tǒng)推導(dǎo)式——計(jì)算兩次
# roots = [math.sqrt(x) for x in range(10) if math.sqrt(x) > 2]
# 海象運(yùn)算符——只計(jì)算一次
roots = [s for x in range(10) if (s := math.sqrt(x)) > 2]
print(roots) # [2.236..., 2.449..., 2.645..., 2.828..., 3.0]
# 更實(shí)際的例子——處理代價(jià)高昂的計(jì)算
def expensive_computation(x):
"""模擬代價(jià)高昂的計(jì)算"""
import time
time.sleep(0.01)
return x ** 2
# 傳統(tǒng)方式:計(jì)算兩次
# result = [expensive_computation(x) for x in range(10)
# if expensive_computation(x) > 50]
# 海象運(yùn)算符:只計(jì)算一次
result = [val for x in range(10)
if (val := expensive_computation(x)) > 50]
print(result) # [64, 81]
# 在條件中使用多次
data = ['hello', 'world', 'hi', 'python', 'hey']
# 找出包含'o'且長度大于4的詞
long_with_o = [w for w in data if 'o' in w and len(w) > 4]
print(long_with_o) # ['hello', 'world', 'python']
六、推導(dǎo)式的性能
6.1 推導(dǎo)式為什么更快
import time
n = 1000000
# 方式一:傳統(tǒng)for循環(huán)
start = time.perf_counter()
result1 = []
for i in range(n):
result1.append(i ** 2)
t1 = time.perf_counter() - start
# 方式二:列表推導(dǎo)式
start = time.perf_counter()
result2 = [i ** 2 for i in range(n)]
t2 = time.perf_counter() - start
# 方式三:map + lambda
start = time.perf_counter()
result3 = list(map(lambda i: i ** 2, range(n)))
t3 = time.perf_counter() - start
print(f'for循環(huán): {t1:.3f}秒')
print(f'推導(dǎo)式: {t2:.3f}秒')
print(f'map + lambda: {t3:.3f}秒')
print(f'推導(dǎo)式比for循環(huán)快 {(t1 / t2 - 1) * 100:.0f}%')
# 推導(dǎo)式快在:
# 1. 循環(huán)在C層面執(zhí)行,不經(jīng)過Python的迭代器協(xié)議
# 2. append方法不需要每次在Python層面查找
# 3. 結(jié)果列表的內(nèi)存可以預(yù)估,減少擴(kuò)容次數(shù)
6.2 推導(dǎo)式 vs 生成器表達(dá)式
import sys
n = 1000000
# 列表推導(dǎo)式——一次性創(chuàng)建整個(gè)列表(占用內(nèi)存)
list_comp = [i ** 2 for i in range(n)]
print(f'列表推導(dǎo)式內(nèi)存: {sys.getsizeof(list_comp):,} 字節(jié)')
# 大約 8MB
# 生成器表達(dá)式——惰性求值(不占內(nèi)存)
gen_expr = (i ** 2 for i in range(n)) # 注意:圓括號(hào)不是元組
print(f'生成器表達(dá)式內(nèi)存: {sys.getsizeof(gen_expr)} 字節(jié)')
# 大約 200 字節(jié)
# 生成器表達(dá)式適合:
# 1. 只需要遍歷一次
# 2. 數(shù)據(jù)量非常大,不想創(chuàng)建中間列表
# 3. 作為函數(shù)參數(shù)傳遞
# 例子:
total = sum(i ** 2 for i in range(10000000)) # 不創(chuàng)建中間列表
# 而不是:
# total = sum([i ** 2 for i in range(10000000)]) # 先創(chuàng)建1000萬的列表!
七、推導(dǎo)式的最佳實(shí)踐與常見誤區(qū)
7.1 什么時(shí)候不該用推導(dǎo)式
# 誤區(qū)一:推導(dǎo)式太長太復(fù)雜——應(yīng)該拆開寫
# 不推薦:一個(gè)推導(dǎo)式做太多事情
# result = [process(x) for y in data if condition(y) for x in y.get_items() if x.status == 'active']
# 這種代碼需要讀者在腦子里編譯好幾次
# 推薦:拆分為多步
active_items = []
for y in data:
if condition(y):
for x in y.get_items():
if x.status == 'active':
active_items.append(process(x))
# 誤區(qū)二:推導(dǎo)式有副作用
# 不推薦:在推導(dǎo)式中做有副作用的事(打印、修改外部變量等)
# result = [print(x) or x for x in data] # 不要這樣寫!
# 推導(dǎo)式應(yīng)該只用于"創(chuàng)建新列表",不應(yīng)該有副作用
# 誤區(qū)三:為了用推導(dǎo)式而用推導(dǎo)式
# 如果for循環(huán)更清晰,就用for循環(huán)
# 代碼清晰度 > 炫技
# 好的推導(dǎo)式:
active_users = [u for u in users if u.is_active] # 簡單清晰
# 可能需要拆開的:
# result = [
# format_item(x) if condition(x) else default_value(x)
# for group in data
# for x in group if x is not None
# ] # 這個(gè)就有點(diǎn)長了
7.2 可讀性檢查清單
# 檢查你的推導(dǎo)式是否可讀:
# 1. 能一句話描述它的作用嗎?
# ? [x for x in data if x > 0] → "取出所有正數(shù)"
# ? 過于復(fù)雜的嵌套
# 2. 所有變量名都清晰嗎?
# ? [user.name for user in active_users]
# ? [x.n for x in u if x.a]
# 3. 可以一眼看到"表達(dá)式"和"數(shù)據(jù)源"嗎?
# ? [f(x) for x in data]
# ? 表達(dá)式和數(shù)據(jù)源混在一起
# 4. 有超過兩個(gè)for嗎?
# 如果是——考慮拆開或用傳統(tǒng)循環(huán)
# 5. 有超過兩個(gè)if嗎?
# 如果是——考慮用輔助函數(shù)
# 良好實(shí)踐的示例:
# 簡單過濾
evens = [x for x in numbers if x % 2 == 0]
# 簡單映射(數(shù)據(jù)轉(zhuǎn)換)
names = [user.name for user in users]
# 過濾+映射
active_names = [user.name for user in users if user.is_active]
# 嵌套(確保可讀)
flat_cells = [cell for row in table for cell in row]
# 構(gòu)建字典(字典推導(dǎo)式)
name_map = {user.id: user.name for user in users}
# 構(gòu)建集合(集合推導(dǎo)式)
unique_tags = {tag for article in articles for tag in article.tags}
八、推導(dǎo)式家族:不只是列表
8.1 字典推導(dǎo)式
# {key_expr: value_expr for item in iterable if condition}
# 基本用法
squares = {x: x ** 2 for x in range(6)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 反轉(zhuǎn)字典的鍵值
original = {'a': 1, 'b': 2, 'c': 3}
reversed_dict = {v: k for k, v in original.items()}
print(reversed_dict) # {1: 'a', 2: 'b', 3: 'c'}
# 過濾
scores = {'小明': 85, '小紅': 92, '小剛': 78, '小李': 95}
passing = {name: score for name, score in scores.items() if score >= 90}
print(passing) # {'小紅': 92, '小李': 95}
# 從兩個(gè)列表構(gòu)建字典
keys = ['name', 'age', 'city']
values = ['小明', 25, '北京']
person = {k: v for k, v in zip(keys, values)}
print(person) # {'name': '小明', 'age': 25, 'city': '北京'}
8.2 集合推導(dǎo)式
# {expr for item in iterable if condition}
# 基本用法
squares = {x ** 2 for x in range(10)}
print(squares) # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
# 去重
words = ['hello', 'world', 'hello', 'python', 'world']
unique_words = {w.lower() for w in words}
print(unique_words) # {'hello', 'world', 'python'}
# 提取所有標(biāo)簽
articles = [
{'title': '文章1', 'tags': ['Python', '編程']},
{'title': '文章2', 'tags': ['Java', '編程']},
{'title': '文章3', 'tags': ['Python', 'Web']},
]
all_tags = {tag for article in articles for tag in article['tags']}
print(all_tags) # {'Python', '編程', 'Java', 'Web'}
九、實(shí)戰(zhàn):推導(dǎo)式解決實(shí)際問題
9.1 數(shù)據(jù)清洗流水線
def clean_dataset(raw_data):
"""用推導(dǎo)式流水線清洗數(shù)據(jù)集"""
# 過濾掉None和空記錄
valid = [r for r in raw_data if r is not None and r]
# 格式化每個(gè)字段
cleaned = [
{
'name': r['name'].strip().title(),
'email': r['email'].strip().lower(),
'age': int(r['age']),
'score': float(r['score']),
}
for r in valid
if r.get('name') and r.get('email') and r.get('age')
]
# 只保留有效分?jǐn)?shù)的記錄
cleaned = [r for r in cleaned if 0 <= r['score'] <= 100]
return cleaned
raw = [
{'name': ' alice ', 'email': 'ALICE@test.com', 'age': '25', 'score': '85.5'},
None,
{},
{'name': 'BOB', 'email': 'bob@test.com', 'age': '30', 'score': '92.0'},
{'name': '', 'email': '', 'age': '0', 'score': '0'},
{'name': ' charlie ', 'email': 'CHARLIE@test.com', 'age': '28', 'score': '105'},
]
cleaned = clean_dataset(raw)
for r in cleaned:
print(r)
9.2 構(gòu)建復(fù)雜數(shù)據(jù)結(jié)構(gòu)
# 生成日歷數(shù)據(jù)
import calendar
import datetime
def month_calendar(year, month):
"""生成一個(gè)月的日歷數(shù)據(jù)(二維列表)"""
cal = calendar.monthcalendar(year, month)
# 標(biāo)注周末
annotated = [
[
{
'day': day,
'is_weekend': i >= 5, # 第6、7列是周末
'is_today': day == datetime.date.today().day
and month == datetime.date.today().month
and year == datetime.date.today().year,
}
if day != 0 else None
for i, day in enumerate(row)
]
for row in cal
]
return annotated
# 生成嵌套菜單
menu_items = ['文件', '編輯', '視圖', '幫助']
sub_items = {
'文件': ['新建', '打開', '保存', '退出'],
'編輯': ['撤銷', '重做', '剪切', '復(fù)制', '粘貼'],
'視圖': ['放大', '縮小', '全屏'],
'幫助': ['關(guān)于', '更新'],
}
menu = [
{
'name': item,
'submenu': [
{'name': sub, 'shortcut': f'Ctrl+{chr(65 + j)}'}
for j, sub in enumerate(sub_items.get(item, []))
]
}
for i, item in enumerate(menu_items)
]
for m in menu:
print(f'{m["name"]}: {[s["name"] for s in m["submenu"]]}')
十、本篇小結(jié)
列表推導(dǎo)式是Python最具代表性的特性之一:
- 基本語法:
[表達(dá)式 for 變量 in 可迭代對(duì)象 if 條件] - 過濾 vs 轉(zhuǎn)換:
if在for后是過濾(減少元素),if-else在for前是轉(zhuǎn)換(元素?cái)?shù)量不變) - 嵌套循環(huán):for的順序和嵌套for循環(huán)一致,外層在前內(nèi)層在后
- 性能:推導(dǎo)式比等價(jià)for循環(huán)快(C層面執(zhí)行),但大量數(shù)據(jù)考慮用生成器表達(dá)式
- 可讀性第一:太復(fù)雜的推導(dǎo)式拆開寫成for循環(huán)更好
- 推導(dǎo)式家族:列表
[x for x in ...]、字典{k:v for k,v in ...}、集合{x for x in ...}、生成器(x for x in ...)
列表推導(dǎo)式是Python編程的"標(biāo)配技能"。當(dāng)你開始習(xí)慣用推導(dǎo)式替代簡單的for循環(huán)后,你會(huì)發(fā)現(xiàn)代碼變得更短、更清晰、更Pythonic。下一篇我們將進(jìn)入列表嵌套與二維列表的操作技巧——矩陣運(yùn)算、棋盤游戲、電子表格等場景的核心數(shù)據(jù)結(jié)構(gòu)。
以上就是Python基礎(chǔ)指南之列表推導(dǎo)式的入門與靈活運(yùn)用的詳細(xì)內(nèi)容,更多關(guān)于Python列表推導(dǎo)式的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python模擬百度自動(dòng)輸入搜索功能的實(shí)例
今天小編就為大家分享一篇Python模擬百度自動(dòng)輸入搜索功能的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-02-02
使用Tensorflow?hub完成目標(biāo)檢測過程詳解
這篇文章主要為大家介紹了使用Tensorflow?hub完成目標(biāo)檢測過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
TensorFlow——Checkpoint為模型添加檢查點(diǎn)的實(shí)例
今天小編就為大家分享一篇TensorFlow——Checkpoint為模型添加檢查點(diǎn)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python使用pickle模塊報(bào)錯(cuò)EOFError Ran out of input的解決方法
這篇文章主要介紹了Python使用pickle模塊報(bào)錯(cuò)EOFError Ran out of input的解決方法,涉及Python異常捕獲操作處理相關(guān)使用技巧,需要的朋友可以參考下2018-08-08
Python爬蟲爬取電影票房數(shù)據(jù)及圖表展示操作示例
這篇文章主要介紹了Python爬蟲爬取電影票房數(shù)據(jù)及圖表展示操作,結(jié)合實(shí)例形式分析了Python爬蟲爬取、解析電影票房數(shù)據(jù)并進(jìn)行圖表展示操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2020-03-03

