根据对象的属性均匀分布对象

2024-06-01 23:20:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法,如何根据要列出的对象的属性均匀地分布对象。你知道吗

例如:

[{'fruit':'apple', 'price':45},{'fruit':'apple', 'price':5},
 {'fruit':'orange','price':4},{'fruit':'orange','price':45},                                    
 {'fruit':'orange','price':8},{'fruit':'orange','price':450},]

我想重新排列这张单子,使所有同类水果尽可能分开。这个简单例子的解决方案是:

[{'fruit':'orange', 'price':45},{'fruit':'apple', 'price':5},
 {'fruit':'orange','price':4},{'fruit':'apple','price':45},                                    
 {'fruit':'orange','price':8},{'fruit':'orange','price':450},]

所以orange,apple,orange,orange,apple,orange是正确的解决方案之一。你知道吗

这是一个简化的例子。事实上,它是关于抓取大量的网址。我使用100个工作人员的池来清理这些URL。同一个站点可以有多个url,所以我想平均分布它们,因为我不想让别人的服务器过载。你知道吗

你知道怎么解决这个问题吗?或者有什么模块可以做到这一点?你知道吗


Tags: 对象方法urlapple属性解决方案price例子
1条回答
网友
1楼 · 发布于 2024-06-01 23:20:03

roundrobinitertools recipe与itertools.groupby组你知道吗

from itertools import cycle, groupby, islice

def roundrobin(*iterables):
    "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))

earls = [{'fruit':'apple', 'price':45},{'fruit':'apple', 'price':5},
         {'fruit':'orange','price':4},{'fruit':'orange','price':45},
         {'fruit':'orange','price':8},{'fruit':'orange','price':450},]

key = operator.itemgetter('fruit')
earls.sort(key = key)
groups = (tuple(group) for key, group in groupby(earls, key))

for thing in roundrobin(*groups):
    print(thing)

结果:

{'fruit': 'apple', 'price': 45}
{'fruit': 'orange', 'price': 4}
{'fruit': 'apple', 'price': 5}
{'fruit': 'orange', 'price': 45}
{'fruit': 'orange', 'price': 8}
{'fruit': 'orange', 'price': 450}
>>> 

相关问题 更多 >