1 回答
TA贡献1779条经验 获得超6个赞
在第一次检查中,去掉 中的逗号和空格err:
for z in n:
if type(z)==list:
x=Validate(z)
if x!='':
err='%s%s' % (err,x) # instead of: err='%s%s, ' % (err,x)
# this will print "Result: err1, err2, suberr1, lasterr, "
对于您的问题,一个可能更Pythonic(或至少更通用)的解决方案可能是编写一个生成器来遍历嵌套列表:
def traverse(o, tree_types=(list, tuple)):
if isinstance(o, tree_types):
for value in o:
for subvalue in traverse(value, tree_types):
yield subvalue
else:
yield o
然后您可以使用它根据您的条件检查每个元素:
>>> a = [n if 'err' in n else '' for n in traverse(testpar)]
['', 'err1', 'err2', 'suberr1', '', '', 'lasterr']
>>> print(", ".join(filter(len,a))) # remove empty strings, convert list to prettier string
'err1, err2, suberr1, lasterr'
添加回答
举报