一:for循环和if-else结合
1:一行实现双层循坏
# 循环遍历 [[],[],[]] list_a = [['Chris Pratt', ' Vin Diesel', ' Bradley Cooper', ' Zoe Saldana'], ['Noomi Rapace', ' Logan Marshall-Green', ' Michael Fassbender', ' Charlize Theron']]list_b = [i for j in list_a for i in j]print(list_b)# ['Chris Pratt', ' Vin Diesel', ' Bradley Cooper', ' Zoe Saldana', 'Noomi Rapace', ' Logan Marshall-Green', ' Michael Fassbender', ' Charlize Theron']
2:一行实现for-与if-else逻辑
a = [i if i >1 else 8 for i in [8,9,7]] # b= [ i for i in [0,1,2,3] if i >0] # 只有if时要写在后面print(a)print(b)
3:Facebook 景霄-07条件与循环_思考题
ps:一行或多行实现 aim_list
attributes = ['name', 'dob', 'gender']values = [['jason', '2000-01-01', 'male'],['mike', '1999-01-01', 'male'],['nancy', '2001-02-01', 'female']]# expected outout:aim_list = [{ 'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'},{ 'name': 'mike', 'dob': '1999-01-01', 'gender': 'male'},{ 'name': 'nancy', 'dob': '2001-02-01', 'gender': 'female'}]# 一行one = [dict(zip(attributes,value)) for value in values ]# 多行more = []temp = {}for index,value in enumerate(values): temp[attributes[index]] = value[index] more.append(temp)print('one:',one)print('more:',more)