Tôi có một danh sách các từ điển, mà tôi muốn sắp xếp vòng xoay.Làm thế nào để "round-robin" một lần lặp lại dựa trên một số tiêu chí?
sample = [
{'source': 'G', '"serial"': '0'},
{'source': 'G', '"serial"': '1'},
{'source': 'G', '"serial"': '2'},
{'source': 'P', '"serial"': '30'},
{'source': 'P', '"serial"': '0'},
{'source': 'P', '"serial"': '1'},
{'source': 'P', '"serial"': '2'},
{'source': 'P', '"serial"': '3'},
{'source': 'T', '"serial"': '2'},
{'source': 'T', '"serial"': '3'}
]
Tôi muốn kết quả này:
sample_solved = [
{'source': 'G', '"serial"': '0'},
{'source': 'P', '"serial"': '30'},
{'source': 'T', '"serial"': '2'},
{'source': 'G', '"serial"': '1'},
{'source': 'P', '"serial"': '1'},
{'source': 'T', '"serial"': '3'},
{'source': 'G', '"serial"': '2'},
{'source': 'P', '"serial"': '0'},
{'source': 'P', '"serial"': '2'},
{'source': 'P', '"serial"': '3'}
]
Con đường tôi giải quyết nó như sau:
def roundrobin(*iterables):
# took from here https://docs.python.org/3/library/itertools.html#itertools-recipes
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
def solve():
items_by_sources = collections.defaultdict(list)
for item in sample2:
items_by_sources[item["source"]].append(item)
t, p, g = items_by_sources.values()
print(list(roundrobin(t, p, g)))
Sử dụng Python của defaultdict
để tách các mặt hàng theo nguồn và sau đó sử dụng các giải pháp roundrobin mà tôi nhận được từ tài liệu của Python.
Nhưng, giải pháp, không bao gồm tất cả các trường hợp, ví dụ t, p, g = items_by_sources.values()
sẽ ngắt khi một nguồn bị thiếu hoặc nguồn mới đã được thêm.
Làm cách nào để tôi có thể đưa ra giải pháp để bao quát thêm các trường hợp cạnh và làm cho dung dịch trở thành pythonic?