【问题标题】:Itertools Group list of dicts of variable length by key/value pairsItertools 按键/值对分组可变长度的字典列表
【发布时间】:2023-02-24 01:39:34
【问题描述】:

我有这个输入对象:

vv = [{'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']},{'values': ['All']}]

...可以存在可变数量的字典,但所有字典都将始终具有键“值”和为此填充的值。

分配给“值”的值类型将始终是字符串或列表。我希望分组/压缩,所以我得到以下输出(元组列表或元组元组很好):

(
('AirportEnclosed', 'All'),
('Bus', 'All'),
('MotorwayServiceStation', 'All')
)

...这是我的代码:

import itertools

outputList=[]
for i,g in itertools.groupby(vv, key=operator.itemgetter("values")):
    outputList.append(list(g))
print(outputList) 

...这是我的输出:

[[{'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']}], [{'values': ['All']}]]

...我需要改变什么?

【问题讨论】:

  • vv 的初始化不是有效的 Python。另外,要求不明确。
  • 为什么它不是有效的 python?输入结构、输出结构和代码有什么不清楚的地方?
  • 为什么不将它复制/粘贴到 Python REPL 中以找出答案。
  • 现在它是。快乐的?
  • 这实际上是您的earlier question 的副本,其中的要求也是模棱两可的。如果很多人都告诉你同样的事情,也许他们是对的而你不是。

标签: python python-3.x python-itertools


【解决方案1】:
import itertools as it

vv = [{'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']}, 
{'values': ['All']}]

tmp = []

for curr_dict in vv:
    val = curr_dict["values"]
    if type(val) == str:
        val = [val]
    tmp.append(val)

pr = it.product(*tmp)
out = []

for i in pr:
    out.append(i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多