3 回答
TA贡献1872条经验 获得超3个赞
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贡献1833条经验 获得超4个赞
我认为它更具可读性:
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贡献1828条经验 获得超3个赞
你可以这样做:
for elem in children:
if children.index(elem) % 2 == 0:
print(f"{elem} to {pools[0]}")
else:
print(f"{elem} to {pools[1]}")
考虑到你只有两个池,如果他的索引是奇数,你可以将孩子分配给 pool1。
添加回答
举报