📜  Python|连接字典值列表

📅  最后修改于: 2022-05-13 01:54:19.667000             🧑  作者: Mango

Python|连接字典值列表

有时,在使用字典时,我们可能会遇到一个问题,即我们将列表作为它的值,并希望通过串联将其累积到单个列表中。此问题可能发生在 Web 开发领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用sum() + values()
这是最推荐的方法,也是执行此任务的一种方法。在此,我们使用values()访问所有列表值,并使用sum()执行连接实用程序。

# Python3 code to demonstrate working of
# Concatenating dictionary value lists
# Using sum() + values()
  
# initializing dictionary
test_dict = {"Gfg" : [4, 5], "is" : [6, 8], "best" : [10]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Concatenating dictionary value lists
# Using sum() + values()
res = sum(test_dict.values(), [])
  
# printing result 
print("The Concatenated list values are : " + str(res))
输出 :
The original dictionary is : {'Gfg': [4, 5], 'best': [10], 'is': [6, 8]}
The Concatenated list values are : [4, 5, 10, 6, 8]

方法 #2:使用chain() + * operator
也可以使用这些方法的组合来执行此任务。在这些中,我们只是使用chain的内置函数来连接列表,并使用 *运算符将所有列表值访问为一个。

# Python3 code to demonstrate working of
# Concatenating dictionary value lists
# Using chain() + * operator
from itertools import chain
  
# initializing dictionary
test_dict = {"Gfg" : [4, 5], "is" : [6, 8], "best" : [10]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Concatenating dictionary value lists
# Using chain() + * operator
res = list(chain(*test_dict.values()))
  
# printing result 
print("The Concatenated list values are : " + str(res))
输出 :
The original dictionary is : {'Gfg': [4, 5], 'best': [10], 'is': [6, 8]}
The Concatenated list values are : [4, 5, 10, 6, 8]