python - 循环遍历每个列表项的函数

标签 python python-3.x

<分区>

我正在使用 Python。

给定一个项目列表,item_list 我试图对每个项目运行一个函数,这些函数应该来自 function_list:

item_list = [item1, item2, item3, item4, item5, item6]
function_list = [myfunction1, myfunction2, myfunction3] 

我想以某种方式遍历项目并将函数关联到它们: 它应该导致这样的调用:

myfunction1(item1)
myfunction2(item2)
myfunction3(item3)
myfunction1(item4)
myfunction2(item5)
myfunction3(item6)

因此列表中的第一项将启动 myfunction1(),第二项 myfunction2() 直到结束,然后它会开始选择从一开始就发挥作用。

谁有我能看到的类似的例子?

最佳答案

您可以压缩和循环。稍后迭代:

from itertools import cycle
... etc ...

for item,func in zip(items_list, cycle(functions)):
    func(item)

这是一个完整的例子:

from itertools import cycle

def myfunction1(item):
    print("f1", item)

def myfunction2(item):
    print("f2", item)

def myfunction3(item):
    print("f3", item)

functions = [myfunction1, myfunction2, myfunction3]

items_list = [1,2,3,4,5,6]

for item,func in zip(items_list, cycle(functions)):
    func(item)

这将允许您在到达终点时从头开始选择函数。

关于python - 循环遍历每个列表项的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35658471/

相关文章:

python - 谷歌应用程序引擎批量加载器 "Unexpected Thread Death"

python-3.x - 使用具有对数损失和 RFECV 的不平衡数据集的问题

python - 如何将两个等长列表转换为表示有序对的嵌套列表列表?

python - 这些子类定义有何不同?

python - urlopen 似乎不起作用,具体取决于输入文本的生成方式

Python类型对照表

python - Django 1.11 模型迁移操作不适用

python - 计算 numpy 矩阵的极分解?

python - 如何在healpy中旋转整个healpix map ?

python - association_proxy 创建者中的 session