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.
I'm also struggling with inserting an "elif" condition in there (for the sake of the argument, changing '1' with 'Y').
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.
d = {'0':'X', '1':'Y', '2':'Z'}
lst = [d[coord] if coord in d else coord for coord in printready]
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With