Python-练习 32 循环和列表

时间:2025-04-07 07:42:25
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes throuth a list for number in the_count: print(f"This is count {number}") # same as above for fruit in fruits: print(f"A fruit of type: {fruit}") #also we can go through mixed lists too #notice we have to use {} since we don't know what's in it for i in change: print(f"I got {i}") #we can also build lists, first start with an empty one elements = [] #then use the range function to do 0 to 5 counts for i in range(0, 6): print(f"Adding {i} to the list.") # append is a function that lists understand elements.append(i)#append() 方法用于在列表末尾添加新的对象。 #now we can print them out too for i in elements: print(f"Element was: {i}") '''-----------------------------------------------------------------------------''' ''' 1. 看看你是如何使用 range 的。查阅上面的 range 函数并理解掌握。 range() 函数可创建一个整数列表,一般用在 for 循环中。 range(start, stop[, step]) 2. 你能在第 22 行不使用 for-loop,而是直接把 range(0, 6) 赋给 elements 吗? 3. 找到 Python 文档关于列表的部分,然后读一读。看看除了 append,你还能对列表做哪些操作? '''