python算術運算和for迴圈
阿新 • • 發佈:2020-11-21
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/11/22 14:34 # @Author : XiaoWei # @Email : [email protected] # @FileName : 推導式.py # @Project : script # 推導式 """ 通過一行迴圈判斷,遍歷一系列資料的方式是推導式 語法: val for val in Iterable (把想要的值解除安裝 for的左側) 裡面是一樣迴圈判斷!根據套在推導式外層的符號判斷具體是什麼型別的推導式 推導式有三種: 列表推導式: [val for val in Iterable] 集合推導式: {val for val in Iterable} 字典推導式: [k:v for k:v in Iterable]""" # 1、普通 list_a = [1, 2, 3, 4] list_b = [] list_c = [] # 普通寫法 for i in list_a: list_b.append(i) print(list_b) # 推導式寫法 res = [i for i in list_a] print(res) # 普通修改 for i in list_a: i = i*2 list_c.append(i) print(list_c) # 推導式寫法 res = [str(i * 2) for i in list_a] print(res) # 2、帶判斷條件 list_a = [1, 2, 3, 4] list_b= [] # 普通 for i in list_a: if i %2 ==0: list_b.append(i) print(list_b) # 推導式寫法 res = [i for i in list_a if i % 2 == 0] print(res) # 3、雙迴圈 list_a = ["a1", "a2", "a3"] list_b = ["b1", "b2", "b3"] list_c = [] # 常規寫法 for i in list_a: for j in list_b: list_c.append(i + " ❤❤ " + j)print(list_c) # 推導式寫法 res = [i + " ❤❤ " + j for i in list_a for j in list_b] print(res) print("<========>") # 帶有判斷條件的雙迴圈 list_a = ["a1", "a2", "a3"] list_b = ["b1", "b2", "b3"] # 常規寫法 list_c = [] for i in list_a: for j in list_b: if list_a.index(i) == list_b.index(j): list_c.append(i + " ❤❤ " + j) print(list_c) # 推導式寫法 res = [i + " ❤❤ " + j for i in list_a for j in list_b if list_a.index(i) == list_b.index(j)] print(res)