基本格式为:
expression for item in sequence if condition
names = ['大湘菜', '小湘菜', '巨大湘菜', '微小湘菜'] # 列表 new_names = [name.upper() for name in names if len(name) > 3] print(new_names) print(type(new_names)) # 字典 new_dict = {name: name[0] for name in names} print(new_dict) print(type(new_dict)) # 集合 new_set = {len(name) ** 2 for name in names} print(new_set) # 自动去掉重复元素 print(type(new_set)) # 元组 new_tuple = (len(name) + 1 for name in names) print(new_tuple) print(type(new_tuple)) # 返回生成器对象
结果为:
['巨大湘菜', '微小湘菜'] <class 'list'> {'大湘菜': '大', '小湘菜': '小', '巨大湘菜': '巨', '微小湘菜': '微'} <class 'dict'> {16, 9} <class 'set'> <generator object <genexpr> at 0x0000026620A09510> <class 'generator'>