2017-03-04 82 views
0

我正在寻找一种方式来根据对象的属性均匀分配对象以进行列表。根据对象的属性均匀分配对象

例如:

[{'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名工作人员的池塘刮掉这些网址。可以有多个具有相同网站的网址,因此我希望平均分配它们,因为我不想重载某些服务器。

你有什么想法解决这个问题吗?还是有一些模块可以做到这一点?

+0

您_apart高达possible_是什么意思?为什么苹果物品不是第一个和最后一个物品? – Arman

+0

因为会有三个桔子相邻,所以这是一个更好的解决方案。 –

+0

总是存在两种“水果”?请多解释一下!你在这里问的不是很明显。 – Arman

回答

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