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 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.