您拥有的代码会将“右”或“左”添加到列表的末尾。
我想你想要这样的东西:
def find_controls(*selection, **kwargs): # with *args you can pass one item, several items, or a list
selection = selection or cmds.ls("*_control") or [] # supplied objects, or the ls command, or an empty list
if not kwargs:
return list(selection) # no flags? reutrn the whole list
lefty = lambda ctrl: ctrl.lower().startswith("left") # this will filter for items with left
righty = lambda ctrl: ctrl.lower().startswith("right") # this will filter for items with left
filters = []
if kwargs.get('left'): # safe way to ask 'is this key here and does it have a true value?'
filters.append(lefty)
if kwargs.get('right'):
filters.append(righty)
result = []
for each_filter in filters:
result += filter (each_filter, selection)
return result
find_controls (left=True, right=True)
# Result: [u'left_control', u'right_control'] #
find_controls (left=True, right =False) # or just left=True
# Result: [u'left_control'] #
find_controls()
# Result: [u'left_control', u'middle_control', u'right_control'] #
这里的技巧是使用lambdas(基本上只是较短格式的函数)和内置过滤器函数(它将函数应用于列表中的所有内容并返回函数为非零、非假的东西答案。很容易看出如何通过添加更多关键字和相应的 lambda 来扩展它