我有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


一些帮助?

最佳答案

干得好:

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]))

关于python - 在python中合并两个不同长度的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56383201/

10-12 22:25