CodeGym /課程 /Python SELF TW /循環與字典生成器

循環與字典生成器

Python SELF TW
等級 11 , 課堂 6
開放

6.1 使用 enumerate()

咱們已經看過如何在字典中使用 keysvaluesitems 進行循環。現在讓我們更深入地了解一下 enumerate() 函數吧。

enumerate() 函數很有用,可以在遍歷字典時提供索引、鍵和值的訪問。

以下是一些使用 enumerate() 與字典的例子:

使用索引遍歷字典的鍵和值

你可以使用 enumerate() 來遍歷字典的鍵和值,同時獲取索引。


# 有關人的字典
person = {"name": "Alice", "age": 25, "city": "New York"}

# 使用索引遍歷字典的鍵和值
for index, (key, value) in enumerate(person.items()):
    print(f"索引: {index}, 鍵: {key}, 值: {value}")
    # 輸出字典每個元素的索引、鍵和值

輸出:


索引: 0, 鍵: name, 值: Alice
索引: 1, 鍵: age, 值: 25
索引: 2, 鍵: city, 值: New York

使用索引轉換字典的值

你可以使用 enumerate() 根據索引來修改字典的值。


# 原始字典
person = {"name": "Alice", "age": 25, "city": "New York"}

# 新字典,值中加入索引
indexed_person = {}
for index, (key, value) in enumerate(person.items()):
    indexed_person[key] = f"{value}_{index}"
    # 把值的字串形式的索引分配給字典中的值

print(indexed_person) 
# 輸出帶有索引的字典值

輸出:


{'name': 'Alice_0', 'age': '25_1', 'city': 'New York_2'}

使用 enumerate() 創建新字典

你可以使用 enumerate() 創建一個新字典,索引作為鍵。


# 原始字典
person = {"name": "Alice", "age": 25, "city": "New York"}

# 新字典,索引作為鍵
indexed_person = {index: (key, value) for index, (key, value) in enumerate(person.items())}
print(indexed_person)
# 輸出以索引作為鍵的新字典

輸出:


{0: ('name', 'Alice'), 1: ('age', 25), 2: ('city', 'New York')}

6.2 字典生成器

咱們已經用過 List Comprehensions 來生成列表,Set Comprehensions 來生成集合。同樣可用生成器語法來創建字典。 Dictionary Comprehensions(字典生成器)讓你能用更簡潔可讀的代碼創建字典。

基本的 dictionary comprehension 語法如下:


{表達式1: 表達式2 for 變量 in 序列 if 條件}

其中

  • 變量 — 從可迭代對象中獲取每個元素值的變量。
  • 序列 — 可迭代對象(如列表、元組、字串),被此變量遍歷。
  • 表達式1 — 用於生成字典鍵的表達式。通常依賴於變量。
  • 表達式2 — 用於生成字典值的表達式。
  • 條件 — (可選)元素要被包括在字典中需要滿足的條件。

例子 1:

創建一個數字平方的字典


# 創建一個字典,鍵是 1 到 5 的數字,值是它們的平方
squares = {x: x ** 2 for x in range(1, 6)}
print(squares)  # 輸出: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

例子 2:

從元組列表創建字典


# 包含鍵值對的元組列表
pairs = [("name", "Alice"), ("age", 25), ("city", "New York")]

# 從元組列表生成字典
person = {key: value for key, value in pairs}
print(person)  # 輸出: {'name': 'Alice', 'age': 25, 'city': 'New York'}

例子 3:

在創建字典時過濾元素


# 創建一個字典,鍵是 1 到 10 的數字,值是它們的平方
# 僅針對偶數
even_squares = {x: x ** 2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)  # 輸出: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

例子 4:

在創建字典時轉換元素


# 字串列表
words = ["apple", "banana", "cherry"]

# 生成字典,鍵是字串,值是字串的長度
word_lengths = {word: len(word) for word in words}
print(word_lengths)  # 輸出: {'apple': 5, 'banana': 6, 'cherry': 6}

嵌套 dictionary comprehensions


# 含有鍵值對的嵌套列表
nested_pairs = [[("a", 1), ("b", 2)], [("c", 3), ("d", 4)]]

# 從嵌套列表生成字典
nested_dict = {key: value for sublist in nested_pairs for key, value in sublist}
print(nested_dict)  # 輸出: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

結合的方法

可以組合不同的字典創建方法來解決更複雜的情況。


# 合併多個字典成一個
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "country": "USA"}
combined_dict = {**dict1, **dict2}
print(combined_dict)  # 輸出: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}

使用 運算符 ** 在字典名稱前,能將其元素解包,就像它們被一一列舉一樣。因此表達式 {**dict1, **dict2} 實際上將兩個字典的元素合併。

留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION