英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论