Python - functions called inside the list. How it works?

I was looking for an algorithm to replace some content inside a list with another. For example, changing all "0" to "X".

I found this piece of code that works:

 list = ['X' if coord == '0' else coord for coord in printready]

What I would like to know is why this works (I understand the logic in the code, not why the compiler accepts this.)

I am also trying to insert the condition "elif" there (for the sake of argument, changing "1" to "Y").

This is probably fully documented, but I have no idea what it's called.

+3
source share
2 answers

. , , . , . ; "".

+7

"elif" ( , "1" "Y" ).

, "elif". , / .

d = {'0':'X', '1':'Y', '2':'Z'}
lst = [d[coord] if coord in d else coord for coord in printready]
+3

Source: https://habr.com/ru/post/1770162/


All Articles