python执行列表和功能列表 [英] python execute list and list of functions

查看:90
本文介绍了python执行列表和功能列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Autodesk Maya中使用Python 2.7.这是我的问题的一个示例:

I'm utilizing Python 2.7 with Autodesk Maya. Here's an example of my issue:

import maya.cmds as m

def a(passedString):
    print('this'+passedString)
def b(passedString):
    print('that'+passedString)
def c(passedString):
    print('notThis'+passedString)
def d(passedString):
    print('ofCourse'+passedString)
string1 = [a(),b(),c(),d()]
string2 = [poly1,poly2,poly3,poly4]
for each in string2 and every in string1:
    m.select(each)
    every(each)

这似乎很简单,但是我需要用string1[0] 并且仅 string1[0]来执行string2[0](一个函数).

This might seem straight forward, but what I need is to have string2[0] (a function) executed with string1[0] and only string1[0].

下一个数组项相同. [1] 带有 [1][2] 带有 [2][3] 带有 [3].

Same goes for the next array item. [1] with [1] and [2] with [2] and [3] with [3].

从本质上讲,我正在努力减少代码并简化我的代码的执行方式,而不是乏味地为20多个单独的实例编写以上代码.

Essentially, I'm trying to cut down on code and simplify how my code executes, as opposed to tediously writing the above code for 20+ individual instances.

推荐答案

您可以zip列表以逐元素方式遍历列表

You can zip the lists to iterate through them in an element-wise fashion

for func, param in zip(string1, string2):
    func(param)

例如

string1 = [len, type, max]
string2 = ['hello', 5, [1,3,7]]
for func, param in zip(string1, string2):
    func(param)

输出

5
<class 'int'>
7

还请注意,在函数列表中,您不应在函数的末尾添加(),因为如果这样做,您将调用.只需保留函数名称本身即可(例如,请参见上面的string1列表).

Also note that in your list of functions you should not add () to the end of the function because you will call the function if you do so. Just leave the function name itself (see the above string1 list for example).

对于您的代码,循环看起来像

For your code the loop would look like

for each, every in zip(string2, string1):
    m.select(each)
    every(each)

这篇关于python执行列表和功能列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆