试图根据一组标准对一组设备进行循环

时间:2017-04-05 07:42:05

标签: python python-3.x itertools

我有2个列表,这两个列表都没有在len中修复。

list1 = ["John", "bruce", "William"]
list2 = ["lindt", "reese", "snickers", "chocolate", "Milkyway", "Cadbury", "Candy"]

我想在list1中的成员中分发糖果,以便最终结果看起来像

John: "lindt","chocolate","candy"
Bruce: "reese","Mlikyway"
Will: "Snickers","Cadbury"

我尝试使用来自cycle的{​​{1}}和zip,但我得到的只是一个类似

的元组
itertools

输出

list1 = ["John","bruce","William"]
list2 = ["lindt","reese","snickers","chocolate","Milkyway","Cadbury","Candy"]
for i in zip(list2,cycle(list1)):
    print(i)

2 个答案:

答案 0 :(得分:0)

让我们使用字典:

kids = {}

list1中的所有成员都会成为词典中的列表:

for i in list1: kids[i] = []

然后使用zip和循环为每个孩子分配糖果:

for i in zip(list2,cycle(list1)): kids[i[1]].append(i[0])
# kids[i[1]] represents the kids's name since it's at index 1 in the tuple
# i[0] represents the candy that is associated to the kid.

结果:

>>> for i in kids: print(i,':', kids[i])
john : ['lindt', 'chocolate', 'candy']
bruce : ['reese', 'milkyway']
william : ['snickers', 'cadbury']

答案 1 :(得分:0)

你非常接近,但你需要一个数据结构来存储这些结果。您也可以使用dict.setdefault

,而不是创建包含键和空列表的字典
from itertools import cycle

d = dict()
for name, item in zip(cycle(list1), list2):
    d.setdefault(name, []).append(item)

print(d)
# {'John': ['lindt', 'chocolate', 'Candy'],
#  'William': ['snickers', 'Cadbury'],
#  'bruce': ['reese', 'Milkyway']}

您也可以使用collections.defaultdict代替setdefault

from itertools import cycle
from collections import defaultdict

d = defaultdict(list)
for name, item in zip(cycle(list1), list2):
    d[name].append(item)

print(d)
# defaultdict(list,
#             {'John': ['lindt', 'chocolate', 'Candy'],
#              'William': ['snickers', 'Cadbury'],
#              'bruce': ['reese', 'Milkyway']})