【问题标题】:Distribute objects evenly according to their attribute根据对象的属性均匀分布对象
【发布时间】:2017-03-04 17:36:23
【问题描述】:

我正在寻找一种方法,如何根据对象的属性均匀分布对象以列出。

例如:

[{'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 是正确的解决方案之一。

这是一个简化的示例。事实上,它是关于抓取大量 url。我使用 100 名工人的池来抓取这些网址。同一个站点可以有多个 url,所以我想平均分配它们,因为我不想让某人的服务器超载。

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

【问题讨论】:

  • 你说的尽可能分开是什么意思?为什么苹果项目不是第一个和最后一个项目?
  • 因为会有三个橙子相邻所以这是一个更好的解决方案。
  • 总是存在两种fruits?请多解释!你在这里问什么并不是很明显。
  • @Arman 我试图在问题的底部解释它。实际上,这是网络抓取问题。例如,我不想让一个站点的 100 个 url 彼此相邻,因为我不想让服务器过载。更好的方法是将这些 url 分布在队列/列表中,这样具有相同站点的 url 就不会被抓取到一个池中。
  • @Arman 那里可以有任意数量的水果(站点)。

标签: python python-2.7 list web-scraping


【解决方案1】:

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}
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多