3 回答

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
from itertools import cycle
pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']
c = cycle(pools)
for child in children:
? ? print('{} assigned to {}'.format(child, next(c)))
印刷:
child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1

TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊
我認(rèn)為它更具可讀性:
from itertools import cycle
pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']
for child, pool in zip(children, cycle(pools)):
? ? print(f'{child} assigned to {pool}')
輸出:
child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
你可以這樣做:
for elem in children:
if children.index(elem) % 2 == 0:
print(f"{elem} to {pools[0]}")
else:
print(f"{elem} to {pools[1]}")
考慮到你只有兩個(gè)池,如果他的索引是奇數(shù),你可以將孩子分配給 pool1。
添加回答
舉報(bào)