列表(list)推导式
# 带有条件的列表推导式
nums = [1, 2, 3, 4, 5]
print([i * i for i in nums if i > 2]) # output:[9, 16, 25]
# 嵌套的列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([j for i in matrix for j in i])
# output:[1, 2, 3, 4, 5, 6, 7, 8, 9]
print([[i for i in range(3)] for j in range(3)])
# output:[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
字典(dict)推导式
# 带有条件的字典推导式
numbers = [1, 2, 3, 4, 5]
print({num: num * num for num in numbers if num > 2}) # output:{3: 9, 4: 16, 5: 25}
keys = ['a', 'b', 'c']
values = [1, 2, 3]
# 嵌套的字典推导式
print({keys[i]: values[i] for i in range(len(keys))}) # output:{'a': 1, 'b': 2, 'c': 3}
print({i: {str(j): i * j for j in range(1, 3)} for i in range(1, 3)})
# output:{1: {'1': 1, '2': 2}, 2: {'1': 2, '2': 4}}
集合(set)推导式
由于集合的无序性和不重复性,使用for…in…循环遍历,虽然顺序不确定,但是可以确保每个元素都会被访问到一次,并且重复的元素对会被自动去除。
# 带有条件的集合推导式
print({i * i for i in range(1, 11) if i % 2 == 0}) # output:{64, 100, 4, 36, 16}
# 嵌套的集合推导式
list1 = [1, 2, 3]
list2 = ['a', 'b']
print({(i, j) for i in list1 for j in list2})
# output:{(1, 'b'), (2, 'a'), (3, 'a'), (2, 'b'), (1, 'a'), (3, 'b')}
元组(tuple)推导式
# 带有条件的元组推导式
print(tuple(i * i for i in range(1, 11) if i % 2 == 0)) # output:(4, 16, 36, 64, 100)
# 嵌套的元组推导式
print(tuple(i * j for i in range(1, 3) for j in range(3, 5))) # output:(3, 4, 6, 8)
标签:推导,16,Python,range,num,print,output
From: https://blog.csdn.net/weixin_60513747/article/details/144108118