我正在努力想出一个有效但简单的解决方案来解决以下问题:
我有两张单子:
list_dicts_1 = [
{"name": "Suarez", "footed": "right-footed", "color": "black"}
{"name": "Suarez2", "footed": "right-footed2", "color": "black2"}
{"name": "Suarez3", "footed": "right-footed3", "color": "black3"}
{"name": "Suarez4", "footed": "right-footed4", "color": "black4"}
{"name": "Suarez5", "footed": "right-footed5", "color": "black5"}
{"name": "Suarez6", "footed": "right-footed6", "color": "black6"}
]
list_dicts_2 = [
{"name": "Coutinho", "footed": "left-footed", "color": "orange"}
{"name": "Coutinho2", "footed": "left-footed1", "color": "orange2"}
{"name": "Coutinho3", "footed": "left-footed2", "color": "orange3"}
{"name": "Coutinho4", "footed": "left-footed4", "color": "orange4"}
{"name": "Coutinho5", "footed": "left-footed5", "color": "orange5"}
{"name": "Coutinho6", "footed": "left-footed6", "color": "orange6"}
]
我想迭代这些dict列表并将它们分配给3个空列表:
list_1 = []
list_2 = []
list_3 = []
期望输出:
list_1 = [
{"name": "Suarez", "footed": "right-footed", "color": "black"},
{"name": "Suarez4", "footed": "right-footed4", "color": "black4"},
{"name": "Coutinho", "footed": "left-footed", "color": "orange"},
{"name": "Coutinho4", "footed": "left-footed4", "color": "orange4"}
]
list_2 = [
{"name": "Suarez2", "footed": "right-footed2", "color": "black2"},
{"name": "Suarez5", "footed": "right-footed5", "color": "black5"},
{"name": "Coutinho2", "footed": "left-footed2", "color": "orange2"},
{"name": "Coutinho5", "footed": "left-footed5", "color": "orange5"}
]
list_3 = [
{"name": "Suarez3", "footed": "right-footed3", "color": "black3"},
{"name": "Suarez6", "footed": "right-footed6", "color": "black6"},
{"name": "Coutinho3", "footed": "left-footed3", "color": "orange3"},
{"name": "Coutinho6", "footed": "left-footed6", "color": "orange6"}
]
我想把这三张单子平分在三张空单子上。字典列表中的每一项只能在空列表中出现一次。所以字典列表的第一行应该放在列表1中。然后第二行的目录应该放在目录2中,以此类推,直到目录里什么都没有了。你知道吗
有没有一个简单的方法来实现这一点?你知道吗
迭代器在这里非常有用:您可以使用^{} 获得一个迭代器,该迭代器在
list_1
、list_2
和list_3
上无限循环。然后简单地迭代list_dicts_1
和list_dicts_2
中的dict并将它们附加到从cycle
获得的列表中:我使用^{} 将} 函数手动推进
list_dicts_1
和list_dicts_2
组合成一个iterable,并使用^{cycle
迭代器。你知道吗结果:
另一种选择是将两个输入列表串联成一个巨大的列表,然后对其进行切片:
但是,串联列表的成本有点高,因此如果列表非常大,应该避免这种情况。你知道吗
可以使用
while
循环:编辑:
也可以使用
for
循环完成!你知道吗编辑2:
它可以做得更好的方式,仍然很容易理解一个初学者
相关问题 更多 >
编程相关推荐