我有2个不同长度的列表。 选择礼物并将其分配给名字,然后将下一个礼物赋予名字,依此类推,直到圈子中的礼物为止。
gifts = ['pencil', 'pen', 'book', 'notebook', 'pencil_box', 'schoolbag', 'stick']
name = ['John', 'Marcus', 'Marie']
预期输出:
John: pencil notebook stick
Marcus: pen pencil_box
Marie: book schoolbag
另一个例子:
gifts = ['car', 'house', 'phone']
name = ['RichieRich']
预期输出:
RichieRich: car house phone
有帮助吗?
答案 0 :(得分:1)
您在这里:
from itertools import cycle
from collections import defaultdict
gifts = ['pencil', 'pen', 'book', 'notebook', 'pencil_box', 'schoolbag', 'stick']
names = ['John', 'Marcus', 'Marie']
gifts_by_name = defaultdict(list)
for name, gift in zip(cycle(names), gifts):
gifts_by_name[name].append(gift)
for name in names:
print '%s: %s' % (name, " ".join(gifts_by_name[name]))
答案 1 :(得分:0)
这可以通过for循环使用:
count = 0
kids = [yourkids]
gifts = [yourgifts]
outputKids = kids
for gift in gifts:
if count > kids.length:
count = 0;
outputKids[count].push(gift)
count = count + 1
然后将您的“孩子”数组映射到您的“ outputKids”(索引方式),就可以得到每个孩子的礼物。