gpt4 book ai didi

一行中的python多个 'for'语句

转载 作者:太空宇宙 更新时间:2023-11-03 12:40:07 24 4
gpt4 key购买 nike

我想对我的代码进行一些重构,我记得在 perl 中有这样的语句(a, b, c) = (x, y, z) 它被称为“多重分配”。我也听说 python 中存在这个东西,但我不需要完全“多重分配”。

我有 3 个相同大小的列表,我需要知道 - 我可以通过这样的方式从它们中获取项目:

for a, b, c in a_list, b_list, c_list:
pass

对于我的测试,它只获取 a_list 的前 3 个元素 (a = a_list[0], b = a_list[1], c = a_list[2]) 但我需要获取一个元素来自 a_list (a = a_list[0]),来自 b_list (b = b_list[0]) 的一个元素和来自 c_list 的相同元素在每次迭代中获取下一个项目。

最佳答案

使用zip :

for a, b, c in zip(a_list, b_list, c_list):
pass

您的代码无效,因为它实际上等同于:

for lis in (a_list, b_list, c_list):
a, b, c = lis #assign the items of list fetched from the `tuple` to a, b ,c

关于一行中的python多个 'for'语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19894715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com