python execute list and list of functions [duplicate]

安稳与你 提交于 2020-01-02 23:36:39

问题


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)

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

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

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.


回答1:


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

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

For example

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

Output

5
<class 'int'>
7

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)


来源:https://stackoverflow.com/questions/28635089/python-execute-list-and-list-of-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!