<p>这是一个纯粹的程序性解决方案,它还增加了选择任意数量、任意规模(甚至比原来的“经纪人”名单还要大)的组的灵活性,并提供了任何补偿:</p>
<pre><code>def get_subgroups(groups, base, size, offset=1):
# cover the group size > len(base) case by expanding the base
# this step is completely optional if your group size will never be bigger
base *= -(-size // len(base))
result = [] # storage for our groups
base_size = len(base) # no need to call len() all the time
current_offset = 0 # tracking current cycle offset
for i in range(groups): # use xrange() on Python 2.x instead
tail = current_offset + size # end index for our current slice
end = min(tail, base_size) # normalize to the base size
group = base[current_offset:end] + base[:tail - end] # get our slice
result.append(group) # append it to our result storage
current_offset = (current_offset + offset) % base_size # increase our current offset
return result
brokers = [1, 2, 3, 4, 5]
print(get_subgroups(5, brokers, 4)) # 5 groups of size 4, with default offset
# prints: [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 1], [4, 5, 1, 2], [5, 1, 2, 3]]
print(get_subgroups(3, brokers, 7, 2)) # 3 groups of size 7, with offset 2
# prints: [[1, 2, 3, 4, 5, 1, 2], [3, 4, 5, 1, 2, 3, 4], [5, 1, 2, 3, 4, 5, 1]]
</code></pre>
<p>它用一个循环在一个O(N)时间内完成。你知道吗</p>
<p>如果您计划在一个非常大的生成器上运行这个函数,您可以通过放弃<code>result</code>集合并执行<code>yield group</code>而不是<code>result.append(group)</code>来将<code>get_subgroups()</code>函数转换为生成器。这样,您就可以在循环中调用它:<code>for group in get_subgroups(30, broker, 4):</code>,并将<code>group</code>存储在您想要的任何结构中。你知道吗</p>
<p><strong>更新</p>
<p>如果内存不是一个问题,我们可以通过扩展整个<code>base</code>(或者在您的情况下是<code>brokers</code>)以适应整个集合来进一步优化(处理方面):</p>
<pre><code>def get_subgroups(groups, base, size, offset=1): # warning, heavy memory usage!
base *= -(-(offset * groups + size) // len(base))
result = [] # storage for our groups
current_offset = 0 # tracking current cycle offset
for i in range(groups): # use xrange() on Python 2.x instead
result.append(base[current_offset:current_offset+size])
current_offset += offset
return result
</code></pre>
<p>或者,如果我们不需要将列表转换为生成器的能力,我们可以通过列表理解使其更快:</p>
<pre><code>def get_subgroups(groups, base, size, offset=1): # warning, heavy memory usage!
base *= -(-(offset * groups + size) // len(base))
return [base[i:i+size] for i in range(0, groups * offset, offset)]
# as previously mentioned, use xrange() on Python 2.x instead
</code></pre>