Last active
December 18, 2015 18:39
-
-
Save inesusvet/5826877 to your computer and use it in GitHub Desktop.
Сложная часть была в том чтобы возвращать через yield пару
ключ+значение и сцеплять ее с текущей последовательностью.
Отлично помогло в этом деле сложение списков
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
def flatter(items): | |
"""Реккурсивный итератор. | |
Обходит все ключи в словаре, работает со спискам любой длины. | |
Исходный словарь предполагается без вложенных словарей. | |
>>> d = {'a': [2, 5, 6], 'b': [8, 3, 6]} | |
>>> map(dict, flatter(d.items())) | |
[{'a': 2, 'b': 8}, {'a': 2, 'b': 3}, {'a': 2, 'b': 6}, {'a': 5, 'b': 8}, {'a': 5, 'b': 3}, {'a': 5, 'b': 6}, {'a': 6, 'b': 8}, {'a': 6, 'b': 3}, {'a': 6, 'b': 6}] | |
""" | |
key, values = items[0] | |
if len(items) == 1: | |
for value in values: | |
yield [(key, value)] | |
else: | |
for value in values: | |
for desc in flatter(items[1:]): | |
yield [(key, value)] + desc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment