python comprehension
python提供了一种语法,让从已存在的集合上创建集合更加容易的办法,英文称为Comprehension.
List comprehesion are used to map input values to output values, applying a filter along the way to include or exclude any values that meet a specific condition.
Example:
input_strings = ["1", "5", "28", "131", "3"]
# without comprehension
output_integers = []
for num in input_strings:
output_integers.append(int(num))
print(output_integers)
# with comprehension
output_integers = [int(num) for num in input_strings]
print(output_integers)
# with filter
output_integers = [int(num) for num in input_strings if len(num) < 3]
print(output_integers)
输出:
[1, 5, 28, 131, 3]
[1, 5, 28, 131, 3]
[1, 5, 28, 3]