在python中嵌套for循环的单行(Nested for loops in python in a single line)
这里有一些代码,我试图让它更具可读性。 它可以工作,但嵌套的for循环和try / if使得第一眼看起来有点难以理解。
有人可以给我关于如何加入嵌套for循环或压缩此代码的建议吗?
matcher = None if re.match(_RE_OBJECT, nodes.replace(LQMN, '')): matcher = alias else: for x in lister[0].conditions: for y in x.codes: try: if y.id.split(',')[1] == condition: matcher = x.codenames except IndexError: passHere is a bit of code that I'm trying to make more readable. It works, but the nested for loops and the try/if makes it a bit hard to understand at first glance what's going on.
Can someone give me suggestions on how I could possibly join the nested for loops or condense this code?
matcher = None if re.match(_RE_OBJECT, nodes.replace(LQMN, '')): matcher = alias else: for x in lister[0].conditions: for y in x.codes: try: if y.id.split(',')[1] == condition: matcher = x.codenames except IndexError: pass最满意答案
您可以使用生成器表达式来嵌套循环并添加一个使IndexError处理程序过时的过滤器:
candidates = ((x, y) for x in lister[0].conditions for y in x.codes if ',' in y.id) for x, y in candidates: if y.id.split(',')[1] == condition: matcher = x.codenames通过使用除x和y之外的更有意义的名称,可读性将得到更多改善:
candidates = ((cond, code) for cond in lister[0].conditions for code in cond.codes if ',' in code.id) for cond, code in candidates: if code.id.split(',')[1] == condition: matcher = cond.codenamesYou could use a generator expression to nest the loops and add a filter that makes the IndexError handler obsolete:
candidates = ((x, y) for x in lister[0].conditions for y in x.codes if ',' in y.id) for x, y in candidates: if y.id.split(',')[1] == condition: matcher = x.codenamesReadability would be improved more by using more meaningful names other than x and y here though:
candidates = ((cond, code) for cond in lister[0].conditions for code in cond.codes if ',' in code.id) for cond, code in candidates: if code.id.split(',')[1] == condition: matcher = cond.codenames更多推荐
发布评论