#範例5-10:串列/數組/列表,list的List Comprehension(綜合表達式,推導式) #推導式功用:可以把一個list(a1),經過推導式,轉寫成第二個list(a2) #https://www.w3schools.com/python/python_lists_comprehension.asp #list的迴圈有3種: #語法1:a3 = a1 + a2 #語法2:a1.extend(a2) ---------------------------- #1.找出有字母o的同學 #Example: #Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. a1 = ["tom","john","mike","jolin"] ---------------------------- #2.找出名字有王的同學 a1 = ["張三王","李四","王五","林九王"] ---------------------------- #3.找出名字不是王五的其它的同學 a1 = ["張三王","李四","王五","林九王"] ---------------------------- #4.找出名字不是王五,李四的其它的同學 a1 = ["張三王","李四","王五","林九王"] --------------------------- #5.將全部同學姓名,轉成大寫 a1 = ["tom","john","mike","jolin"] ---------------------------- #6.把張三王,改成張三 a1 = ["張三王","李四","王五","林九王"] ---------------------------- #7.產生數字資料1,2,3......10 ---------------------------- #8.產生數字資料0,2,3......9 -------------------------------------------------- ----------------------------------------------------------- #範例5-10:串列/數組/列表,list的List Comprehension(綜合表達式,推導式) #推導式功用:可以把一個list(a1),經過推導式,轉寫成第二個list(a2) #https://www.w3schools.com/python/python_lists_comprehension.asp #list的迴圈有3種: #語法1:a3 = a1 + a2 #語法2:a1.extend(a2) #1.找出有字母o的同學 #Example: #Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. a1 = ["tom","john","mike","jolin"] a2 = [item for item in a1 if 'o' in item] print(a2) #2.找出名字有王的同學 a1 = ["張三王","李四","王五","林九王"] a2 = [item for item in a1 if '王' in item] print() print(a2) #3.找出名字不是王五的其它的同學 a1 = ["張三王","李四","王五","林九王"] a2 = [item for item in a1 if item != "王五"] print() print(a2) #4.找出名字不是王五,李四的其它的同學 a1 = ["張三王","李四","王五","林九王"] a2 = [item for item in a1 if item != "王五" and item != "李四"] print() print(a2) #5.將全部同學姓名,轉成大寫 a1 = ["tom","john","mike","jolin"] a2 = [item.upper() for item in a1] print() print(a2) #6.把張三王,改成張三 a1 = ["張三王","李四","王五","林九王"] a2 = [item if item !="張三王" else "張三" for item in a1 ] #The expression in the example above says: #"Return the item if it is not banana, if it is banana return orange". #如果item不等於張三王則傳回item,否則傳回張三 print() print(a2) #7.產生數字資料1,2,3......10 a1 = [i for i in range(1,11,1)] print() print(a1) #8.產生數字資料0,2,3......9 a1 = [i for i in range(10)] print() print(a1) -----------------------------------------------------------