發表文章

目前顯示的是 5月, 2021的文章

python-for其他用法補充

 grade_list = [("小雞", 100), ("兩大類", 0), ("小喵", 80), ("小蟲", 60)] for item in grade_list:     print (item[0], item[1]) print ('---------------------') # 可以直接改寫 for (name, grade) in grade_list:     print (name, grade) print ('---------------------') # 或是這樣 for name, grade in grade_list:     print (name, grade)      print ('---------------------') num_list = [1, 2, 3] for num in num_list:     print (num)     num_list.remove(num) print (num_list) print ('---------------------') num_list = [1, 2, 3] for num in num_list[:]:     print (num)     num_list.remove(num) print (num_list) print ('---------------------') fruits = ['apple', 'banana', 'orange'] for i in fruits:     print(i) print ('---------------------') fruits = ['apple', 'banana', 'orange'] for i in range(len(fruits)):     print(fruits[i]) print ('---------------------') # 反轉 fruits = ['a

python-自訂函式裡的for迴圈存成變數

 def area(width, height):     return width * height   def print_welcome(name):     print("Welcome", name)     global test     test = []     sequences = [0, 1, 2, 3, 4, 5]     for i in sequences:         print(i)         test.append(i)     print (test)     global test1     test1 = ''.join(str(e) for e in test)     #list1 = ['1', '2', '3']     #str1 = ''.join(list1)           print_welcome("Runoob") w = 4 h = 5 print("width =", w, " height =", h, " area =", area(w, h)) print (test1) output如下: D:\>python test.py Welcome Runoob 0 1 2 3 4 5 [0, 1, 2, 3, 4, 5] width = 4  height = 5  area = 20 012345

python-for迴圈其他用法

 word = 'hello' for index, value in enumerate(word,5):     print(index, value) print ('-----------------') #不使用 enumerate() i = 0 word = 'testaaaa' for value in word:     print(i, word[i])     i += 1 print ('-----------------') #使用enumerate() word = 'hello world' for i in enumerate(word):     print(i) print ('-----------------') #迭代字串(string) for i in 'Wow!':     print(i) print ('-----------------') #迭代串列(list) breakfast = ['egg', 'milk', 'apple', 'sandwich'] for food in breakfast:     print(food) print ('-----------------') #迭代字典的鍵(key) desserts = {'Muffin':39, 'Scone':25, 'Biscuit':20} for key in desserts:     print(key)      print ('-----------------') #迭代字典的值(value) desserts = {'Muffin':39, 'Scone':25, 'Biscuit':20} for value in desserts.values():     print(value) print ('-----------------') #迭代字典的鍵(key)及值(value) des

python-for用法

 假設我們想要將for迴圈的資料存成變數,其實可以利用一個空list方式來存取 test = [] sequences = [0, 1, 2, 3, 4, 5] for i in sequences:     print(i)     test.append(i) print (test) test1 = ''.join(str(e) for e in test) #list1 = ['1', '2', '3'] #str1 = ''.join(list1) print (test1) output如下 D:\>python test.py 0 1 2 3 4 5 [0, 1, 2, 3, 4, 5] 012345