1. 列表(list)推导式
基本格式:[x for x in data if condition]
[x for x in range(50) if x%2!=0]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
2.字典(dict)推导式
基本格式:{x:condition for x in data}
{x:x%2!=0 for x in range(50)}
{0: False, 1: True, 2: False, 3: True, 4: False, 5: True, 6: False, 7: True, 8: False, 9: True, 10: False, 11: True, 12: False, 13: True, 14: False, 15: True, 16: False, 17: True, 18: False, 19: True, 20: False, 21: True, 22: False, 23: True, 24: False, 25: True, 26: False, 27: True, 28: False, 29: True, 30: False, 31: True, 32: False, 33: True, 34: False, 35: True, 36: False, 37: True, 38: False, 39: True, 40: False, 41: True, 42: False, 43: True, 44: False, 45: True, 46: False, 47: True, 48: False, 49: True}
3.集合(set)推导式
基本格式:{x for x in data if condition}
{x for x in [1,1,1,2,2,3,4,5,5,6,7,8,8,9,9,10] if x%2!=0}
{1, 3, 5, 7, 9}