创建数字列表
for value in range(1,5): print(value,end=" ")#1 2 3 4 print() #使用range可以生成一个指定范围的数字集合 numbers = list(range(2,7)) print(numbers)#[2, 3, 4, 5, 6] #使用range也可以指定步长来生成数字集合 numbers = list(range(2,10,2)) print(numbers)#[2, 4, 6, 8]步长是2 #使用**2来实现一个数的平方 lst = list() for value in range(1,11): lst.append(value**2) print(lst)#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#对数字列表进行简单地统计计算 lst = list() for value in range(1,11): lst.append(value**2) print(min(lst))#1 print(max(lst))#100 print(sum(lst))#385
#利用解析来创建列表,将for循环和平方写成一行 lst = list([value ** 2 for value in range(1,11)]) print(lst) #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#列表的切片 lst = list(value ** 2 for value in range(1,11))#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] print(lst[2:5]) #[9, 16, 25],从索引值2开始,打印到索引值位4的部分 print(lst[:5]) #[1, 4, 9, 16, 25] 默认是从索引值0开始的 print(lst[2:]) #[9, 16, 25, 36, 49, 64, 81, 100]默认是打到最后 #负数索引返回距离列表相应距离的元素 print(lst[-3:]) #[64, 81, 100] print(lst[:-3]) #[1, 4, 9, 16, 25, 36, 49] #如果要遍历部分切片,可以在for循环内部写上切片 for value in lst[2:9:2]: print(value,end=" ")
#列表的复制,切记不要直接使用myFrinedFoof = myFood myFood = ["pizza","falafel","carrot cake"] myFrinedFoof = myFood[:] myFood.append("apple") #['pizza', 'falafel', 'carrot cake', 'apple'] myFrinedFoof.append("banana") #['pizza', 'falafel', 'carrot cake', 'banana'] print(myFrinedFoof) print(myFood)
#if和列表的结合应用 avaliable_toppings = ["mushroom","oLive","green peppers", "pepperoni","pineapple","extra cheese"] requested_toppings = ["mushroom","french fries","extra cheese"] for requested_topping in requested_toppings: if requested_topping in avaliable_toppings: print("Adding " + requested_topping + ".") else: print("Sorry , We don't have " + requested_topping + "." )