python 列表推导
python
List Comprehensions
List Comprehensions
List comprehensions are an elegant way to build a list without having to use different for loops to append values one by one.
最简单形式
[ expression-involving-loop-variable for loop-variable in sequence ]
if __name__ == "__main__":
print [i for i in range(10)]
nested形式
[ expression-involving-loop-variables for outer-loop-variable in outer-sequence for inner-loop-variable in inner-sequence ]
与以下代码等价:
results = []
for outer_loop_variable in outer_sequence:
for inner_loop_variable in inner_sequence:
results.append( expression_involving_loop_variables )
filter形式
[ expression-involving-loop-variable for loop-variable in sequence if boolean-expression-involving-loop-variable
示例:
>> ListOfThreeMultiples = [x for x in range(10) if x % 3 == 0]
# Multiples of 3 below 10
>> ListOfThreeMultiples
[0, 3, 6, 9]
时间: 2024-10-11 01:02:57