如何在Maya Python脚本中忽略特定字符串,避免其加入列表
Maya Python脚本过滤特定字符串方案
问题说明
编写Maya Python脚本时,希望忽略特定字符串(比如front),不让它被添加到names列表中。之前尝试在初始if循环里用names.remove("front")但没效果,需要可行的实现方法。
原代码
import maya.cmds as mc outliner = mc.ls(type='transform') lists=[] names=[] for i in outliner: if not '|' in i: names.append(i) if '|' in i: lists.append(i.split('|')) for i in lists: names.append(i[len(i)-1]) projPath = mc.workspace( q=True, dir=True )+'Outliner.txt' print(projPath) f = open(projPath,'w') f.write('{0:*^50}'.format('Outliner structure')+'\n') for i in outliner: #print(i) f.write(i+'\n') f.close()
解决方案
你之前用names.remove("front")无效的原因是:如果当前遍历的元素里没有front,调用remove会直接报错;而且即便有,也是先把元素添加到列表再删除,多此一举还容易出问题。正确的思路是在添加元素到列表前就做判断,直接跳过目标字符串。
1. 精确过滤front(完全匹配才跳过)
修改代码中添加元素到names的逻辑,在append前加上判断条件:
import maya.cmds as mc outliner = mc.ls(type='transform') lists=[] names=[] for i in outliner: if not '|' in i: # 精确匹配时跳过"front" if i != "front": names.append(i) if '|' in i: lists.append(i.split('|')) for i in lists: last_name = i[-1] # 用i[-1]代替len(i)-1更简洁 if last_name != "front": names.append(last_name) projPath = mc.workspace( q=True, dir=True )+'Outliner.txt' print(projPath) # 如果需要写入文件时也过滤掉"front"相关元素 f = open(projPath,'w') f.write('{0:*^50}'.format('Outliner structure')+'\n') for i in outliner: # 处理带层级的元素,检查最后一段是否是front if '|' in i: if i.split('|')[-1] != "front": f.write(i+'\n') else: if i != "front": f.write(i+'\n') f.close()
2. 模糊过滤(包含front的字符串都跳过)
如果需要过滤所有包含front的元素(比如front_grp、left_front这类),把判断条件改成'front' not in i即可:
import maya.cmds as mc outliner = mc.ls(type='transform') lists=[] names=[] for i in outliner: if not '|' in i: if 'front' not in i: names.append(i) if '|' in i: lists.append(i.split('|')) for i in lists: last_name = i[-1] if 'front' not in last_name: names.append(last_name) projPath = mc.workspace( q=True, dir=True )+'Outliner.txt' print(projPath) f = open(projPath,'w') f.write('{0:*^50}'.format('Outliner structure')+'\n') for i in outliner: # 检查整个路径是否包含front,或者单独检查最后一段,按需选择 if 'front' not in i: f.write(i+'\n') f.close()
关键要点
- 优先在添加元素前做判断,避免后续删除操作的潜在错误
- 用
i[-1]代替i[len(i)-1]可以让代码更简洁易读 - 根据需求选择精确匹配或模糊匹配的过滤逻辑
- 如果需要写入文件时也过滤,同步修改文件写入的循环判断
内容的提问来源于stack exchange,提问作者variantpolygon
相关产品推荐
相关产品推荐

