(相关资料图)
基本用法 {expression for item in iterable}这是最基本的集合推导式形式。它会对可迭代对象中的每个元素应用一个表达式,将结果放入一个集合中。例如,下面的代码使用集合推导式创建一个包含1到10的平方的集合:
squares = {x*x for x in range(1, 11)}print(squares) # 输出 {1, 4, 9, 16, 25, 36, 49, 64, 81, 100}
2、加入条件{expression for item in iterable if condition}下面的代码使用集合推导式创建一个包含1到10之间的奇数的平方的集合:
odd_squares = {x*x for x in range(1, 11) if x % 2 == 1}print(odd_squares) # 输出 {1, 9, 25, 49, 81}
3、嵌套迭代{expression for item1 in iterable1 for item2 in iterable2}下面的代码使用集合推导式创建一个包含1到10和A到E之间的字符的集合
characters = {str(x) + letter for x in range(1, 11) for letter in "ABCDE"}print(characters) # 输出 {"6A", "7D", "1C", "9D", "4B", "10D", "8E", "3D", "2C", "7B", "1E", "9A", "4C", "6B", "8B", "10E", "3B", "2D", "5C", "1B", "9E", "4E", "6C", "8A", "10B", "3A", "2E", "7E", "5B", "5D", "1A", "9B", "4A", "6E", "8D", "10C", "3E", "2B", "7C", "5A", "5E", "1D", "9C", "4D", "6D", "8C", "10A", "3C", "2A"}
4、嵌套条件{expression for item1 in iterable1 if condition1 for item2 in iterable2 if condition2},下面的代码使用集合推导式创建一个包含1到10之间的奇数的平方的集合,但不包括3的平方
odd_squares = {x*x for x in range(1, 11) if x % 2 == 1 if x != 3}print(odd_squares) # 输出 {81, 1, 25, 49}
5、条件嵌套{expression1 if condition1 else expression2 for item in iterable},下面的代码使用集合推导式创建一个包含1到10之间的奇数的平方的集合,并将偶数设置为0
odd_squares_zero_even = {x*x if x % 2 == 1 else 0 for x in range(1, 11)}print(odd_squares_zero_even) # 输出 {1, 0, 9, 0, 25, 0, 49, 0, 81, 0}
6、带有嵌套迭代和条件的集合推导式{expression for item1 in iterable1 for item2 in iterable2 if condition},下面的代码使用嵌套迭代和条件创建一个包含1到10之间所有奇数的平方和5到10之间所有偶数的平方的集合
odd_squares_even_squares_set = {x*x for x in range(1, 11) if x % 2 == 1} | {x*x for x in range(5, 11) if x % 2 == 0}print(odd_squares_even_squares_set) # 输出 {1, 9, 16, 25, 36, 49, 64, 81, 100}
7、各种类型的字典推导式,见字典推导式
标签:
X 关闭
X 关闭