Mục lục bài viết
Update: 2021-12-24 04:21:11,Bạn Cần tương hỗ về List comprehension if-else. You trọn vẹn có thể lại Báo lỗi ở cuối bài để Mình đc tương hỗ.
List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. List comprehension in Python is also bounded within square brackets, but instead of the list of data inside it, we enter an expression followed by for loops and if-else clauses.
Syntax:
list_variable = [expression for iterator in sequence]
The above syntax, if you can relate, closely resembles the set-builder notation in mathematics.
Set builder form:
S = x² : x in 0 … 5
List Comprehension:
S = [x**2 for x in range(6)]
If we only want to extract expression output for a specific set of data from the entire collection of elements, we can use an if clause after the for loop. The expression will be added to the list only if the if clause is True. Even more than one if clause is allowed, and only if the if clauses return True, do the expressions stay in the list.
Syntax:
[expression for x in sequence if condition]
Example:
LIST = [1,2,3,4,5,6,7,8,9,10]
list = [x for x in LIST if x % 2 == 0]
print(list)
output:
The if-else clause:
Syntax:
[variable if expression else expression for variable sequence]
Example:
LIST = [1,2,3,4,5,6,7,8,9,10]
list = [“EVEN” if i % 2 == 0 else i for i in range(10)]
print(list)
output:
The usage of if-else clauses work the same as the ternary operator ?:
Note: We must use both if and else keywords otherwise a SyntaxError is thrown. We cant use elif here.
Reply
7
0
Chia sẻ
– Một số Keywords tìm kiếm nhiều : ” đoạn Clip hướng dẫn List comprehension if-else tiên tiến và phát triển nhất , Chia Sẻ Link Down List comprehension if-else “.
Bạn trọn vẹn có thể để lại phản hồi nếu gặp yếu tố chưa hiểu nhé.
#List #comprehension #ifelse