列表生成式
- 有返回值
- 基础语法格式:[expression for element in iterable]
new_list = [i for i in range(3)]
'''new_list = [0, 1, 2]'''
new_list = [i for i in ['python', 'java'] if i == 'python']
'''new_list = ['python']'''
new_list = [i if i>5 else 0 for i in range(10)]
'''new_test = [0, 0, 0, 0, 0, 0, 6, 7, 8, 9] '''
new_list = [i[-1] if '*' in i else i for i in [' * a', 'b ', 'c *']]
'''new_list = ['a', 'b ', '*']'''
map
- 有返回值,返回值为map对象,需做数据类型转换
- 基础语法:map(function, iterable, …)
- 可有多个可迭代对象
- 以下以 map + lambda 举例
map_obj = map(lambda i:i if i>5 else round(i/3), range(10))
new_list = list(map_obj)
'''new_list = [0, 0, 1, 1, 1, 2, 6, 7, 8, 9]'''
map_obj = map(lambda a,b: abs(a-b), [3,1,2], [9, 4, 6])
new_list = list(map_obj)
'''new_list = [6, 3, 4]'''
map_obj = map(lambda a: abs(a), [3, 1, 2], [9, 4, 6])
new_list = list(map_obj)
'''异常: <lambda>() takes 1 positional argument but 2 were given'''
filter