📜  Python – 字典值列表中的按列元素

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

Python – 字典值列表中的按列元素

给定带有值列表的字典,按列提取元素。

方法 #1:使用生成器表达式 + zip() + *运算符

在此,我们使用 zip() 执行按列提取的任务,并且 *运算符用于解包值以在生成器表达式中进一步展平。

Python3
# Python3 code to demonstrate working of 
# Column-wise elements in Dictionary value list
# Using generator expression + zip() + * operator
  
# initializing dictionary
test_dict = {'Gfg' : [3, 6, 7],
             'is' : [4, 2, 6], 
             'best' :[9, 1, 3]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values() gets all values at on
res = list(a for b in zip(*test_dict.values()) for a in b)
  
# printing result 
print("The extracted values : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Column-wise elements in Dictionary value list
# Using chain.from_iterable() + zip() + * operator
from itertools import chain
  
# initializing dictionary
test_dict = {'Gfg' : [3, 6, 7],
             'is' : [4, 2, 6], 
             'best' :[9, 1, 3]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values() gets all values at on
res = list(chain.from_iterable(zip(*test_dict.values())))
  
# printing result 
print("The extracted values : " + str(res))


输出
The original dictionary is : {'Gfg': [3, 6, 7], 'is': [4, 2, 6], 'best': [9, 1, 3]}
The extracted values : [3, 4, 9, 6, 2, 1, 7, 6, 3]

方法 #2:使用 chain.from_iterable() + zip() + *运算符

在此,展平任务是使用 chain.from_iterable() 完成的。其余所有功能与上述方法类似。

Python3

# Python3 code to demonstrate working of 
# Column-wise elements in Dictionary value list
# Using chain.from_iterable() + zip() + * operator
from itertools import chain
  
# initializing dictionary
test_dict = {'Gfg' : [3, 6, 7],
             'is' : [4, 2, 6], 
             'best' :[9, 1, 3]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# values() gets all values at on
res = list(chain.from_iterable(zip(*test_dict.values())))
  
# printing result 
print("The extracted values : " + str(res)) 
输出
The original dictionary is : {'Gfg': [3, 6, 7], 'is': [4, 2, 6], 'best': [9, 1, 3]}
The extracted values : [3, 4, 9, 6, 2, 1, 7, 6, 3]