List理解
常见的应用是制作新的列表,其中每个元素是应用于另一个序列的每个成员或可迭代的一些操作的结果,或为这些元素创建满足条件的新的列表:
#List Comprehensions """Common applications are to make new lists where each element is the result of some operations applied toeach member of another sequence or iterable, or to create a subsequence of those elements thatsatisfy a certain condition.""" squares = []for x in range(10): squares.append(x**2) print(squares)print(x)"""Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:"""squares1 = list(map(lambda y: y**2, range(10)))print(squares1)#print(y) Err: y is not defined squares3 = [z**2 for z in range(10)]print(squares3)#print(z) Err: z is not defined 运行结果:
D:\Python3.6.1\python.exe F:/python_workspace/tutorial/Lists3.py
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
9
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Process finished with exit code 0
包含[]的List表达式可以通过for语句,通过0个或多个for或if语句。
"""A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. """result1 = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]print(result1)i = j = 0while( i < 7): print("-------------------") while(j < 2 ): print(result1[i][j]) j = j + 1 j = 0 i = i +1 continue
运行结果:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
-------------------
1
3
-------------------
1
4
-------------------
2
3
-------------------
2
1
-------------------
2
4
-------------------
3
1
-------------------
3
4
学习参考:https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
时间: 2024-10-12 15:40:32