在python中嵌套for循环的单行(Nested for loops in python in a single line)

编程入门 行业动态 更新时间:2024-10-27 22:21:16
在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: pass

Here 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.codenames

You 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.codenames

Readability 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

更多推荐

本文发布于:2023-08-06 03:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1443982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   Nested   python   line   single

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!