Itertools按键/值对对变长字典列表进行分组

huangapple go评论55阅读模式
英文:

Itertools Group list of dicts of variable length by key/value pairs

问题

我有这个输入对象:

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

...可能会有不同数量的字典存在,但所有字典都会始终具有键'values'并为其填充值。

分配给'values'的值将始终是字符串或列表。我希望将它们分组/组合,以便获得以下输出(元组的列表或元组的元组均可):

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

这是我的代码:

import itertools

outputList = []
for i, g in itertools.groupby(vv, key=lambda x: x['values']):
    outputList.append(list(g))
print(outputList)

...这是我的输出:

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

需要进行以下更改:

import itertools

outputList = []
for key, group in itertools.groupby(vv, key=lambda x: x['values']):
    values = list(group)
    if isinstance(key, list):
        for v in key:
            outputList.append((v,) + tuple(item['values'][0] for item in values))
    else:
        outputList.append((key,) + tuple(item['values'][0] for item in values))
print(outputList)

这将给你期望的输出:

[('AirportEnclosed', 'All'), ('Bus', 'All'), ('MotorwayServiceStation', 'All')]
英文:

I have this input object:

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

...there can be variable numbers of dicts present, but all dicts will always have the key 'values' and values populated for this.

The type of value assigned to 'values' will always be string or list. I wish to group/zip so I get the following output (list of tuples or tuple of tuples is fine):

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

...this is my code:

import itertools

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

...and this is my output:

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

...what do I need to change?

答案1

得分: 2

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)
英文:
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)

huangapple
  • 本文由 发表于 2023年2月23日 20:27:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定