Python程式:透過重複鍵對應值次數將字典轉換為列表


在 Python 中,字典是鍵值對,其中每個鍵都與一個對應的值相關聯。當我們想要透過重複鍵來將字典轉換為列表時,我們需要遍歷每個鍵值對,並根據其對應的值重複鍵。

輸入輸出場景

請檢視以下輸入輸出場景,以瞭解將字典轉換為列表(透過重複鍵對應值中的數字)的概念。

Input dictionary: {'a': 3, 'b': 2, 'c': 1}
Output list: ['a', 'a', 'a', 'b', 'b', 'c']

在輸入字典中,鍵 'a' 的值為 3,'b' 的值為 2,'c' 的值為 1,因此在輸出列表中,a 重複三次,b 重複兩次,c 重複一次。

在本文中,我們將瞭解將字典轉換為列表的不同方法,這些方法都是基於根據對應值中的數字重複鍵。

使用 itertools 模組

Itertools 是 Python 標準庫中的一個模組,它提供了一組用於高效且方便地進行迭代相關操作的函式。

在這種方法中,我們使用了 itertools 模組的 chain.from_iterable 函式。我們使用生成器表示式 (key, value) for key, value in the dictionary.items() 遍歷字典中的每個鍵值對。在生成器表示式中,我們將使用 itertools.repeat() 方法重複每個鍵,重複次數為值。然後,chain.from_iterable 函式將結果可迭代物件展平為單個序列。

示例

以下是如何使用 itertools 模組將字典轉換為列表(透過重複鍵對應值)的示例。

import itertools

# Define the function
def dictionary_to_list(dictionary):
    result = list(itertools.chain.from_iterable(itertools.repeat(key, value) for key, value in dictionary.items()))
    return result

# Create the dictionary  
input_dict = {'red': 3, 'yellow': 2, 'green': 3}
print('Input dictionary:', input_dict)

resultant_list = dictionary_to_list(input_dict)
print('Output list:', resultant_list)

輸出

Input dictionary: {'red': 3, 'yellow': 2, 'green': 3}
Output list: ['red', 'red', 'red', 'yellow', 'yellow', 'green', 'green', 'green']

使用 for 迴圈

在這種方法中,我們將使用 for 迴圈來遍歷字典中的每個鍵值對,使用 items() 方法。對於每一對,我們將透過重複鍵來擴充套件結果列表,重複次數等於對應的值。這是透過使用 extend 方法和乘法運算子實現的。

示例

在此示例中,我們將使用 for 迴圈、dict.items() 和 list.extend() 方法將字典轉換為列表(透過重複鍵對應值)。

# Define the function
def dictionary_to_list(dictionary):
    result = []
    for key, value in dictionary.items():
        result.extend([key] * value)
    return result

# Create the dictionary 
input_dict = {'apple': 1, 'banana': 3, 'orange': 4}
print('Input dictionary:', input_dict)

resultant_list = dictionary_to_list(input_dict)
print('Output list:', resultant_list)

輸出

Input dictionary: {'apple': 1, 'banana': 3, 'orange': 4}
Output list: ['apple', 'banana', 'banana', 'banana', 'orange', 'orange', 'orange', 'orange']

使用列表推導式

此方法的工作原理與前一種方法類似,在這裡我們將使用列表推導式來遍歷字典中的鍵值對。對於每一對,鍵將使用 range() 函式重複值次數。

示例

以下是如何使用列表推導式將字典轉換為列表(透過重複鍵對應值)的另一個示例。

# Define the function
def dictionary_to_list(dictionary):
    result = [key for key, value in dictionary.items() for _ in range(value)]
    return result

# Create the dictionary 
input_dict = {'cat': 3, 'dog': 1, 'Parrots': 4}

print('Input dictionary:', input_dict)

resultant_list = dictionary_to_list(input_dict)
print('Output list:', resultant_list)

輸出

Input dictionary: {'cat': 3, 'dog': 1, 'Parrots': 4}
Output list: ['cat', 'cat', 'cat', 'dog', 'Parrots', 'Parrots', 'Parrots', 'Parrots']

以上是使用 Python 程式設計將字典轉換為列表(透過重複鍵對應值)的三個不同示例。

更新於:2023年8月29日

88 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告