Python - 在列表括号内调用的函数。它是如何运作的?
我正在寻找一种算法来将列表中的某些内容替换为另一个内容。例如,将所有“0”更改为“X”。
我找到了这段代码,它有效:
list = ['X' if coord == '0' else coord for coord in printready]
我想知道的是为什么它有效(我理解代码中的逻辑,而不是编译器接受它的原因。)
我也在努力插入一个“elif”那里的条件(为了论证,将“1”更改为“Y”)。
这可能有完整的记录,但我不知道这东西叫什么。
I was looking for an algorithm to replace some content inside a list with another. For instance, changing all the '0' with 'X'.
I found this piece of code, which works:
list = ['X' if coord == '0' else coord for coord in printready]
What I would like to know is exactly why this works (I understand the logic in the code, just not why the compiler accepts this.)
I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').
This is probably thoroughly documented, but I have no idea on what this thing is called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这种构造称为列表理解。这些看起来类似于生成器表达式,但略有不同。列表推导式预先创建一个新列表,而生成器表达式则根据需要创建每个新元素。列表推导式必须是有限的;发电机可能是“无限的”。
This construction is called a list comprehension. These look similar to generator expressions but are slightly different. List comprehensions create a new list up front, while generator expressions create each new element as needed. List comprehensions must be finite; generators may be "infinite".
如果你要替换多个变量,我会使用字典而不是“elif”。这使您的代码更易于阅读,并且可以轻松添加/删除替换。
If you're going to substitute multiple variables, I would use a dictionary instead of an "elif". This makes your code easier to read, and it's easy to add/remove substitutions.