创建数值列表
使用 range
函数, 得到的元素属于:[start, stop)
1 2 for value in range(1 , 10 , 2 ): print(value)
使用list函数,构建一个列表
1 2 for elem in list(range(1 ,10 ,3 )): print(elem)
使用append
函数
1 2 3 4 5 squares = [] for value in range(1 , 5 ): squares.append(value ** 2 ) print(squares)
使用切片构建一个新的列表
1 2 3 4 5 6 7 8 9 my_foods = ['pizza' , 'falafel' , 'carrot cake' ] friend_foods = my_foods[:] friend_foods.append('ice cream' ) print("My favorite foods are:" ) print(my_foods) print("\nMy friend's favorite foods are:" ) print(friend_foods)
列表操作
列表排序操作
改变原来list的排序法: sort
属性
1 2 3 cars = ['bmw' , 'audi' , 'toyota' , 'subra' ] cars.sort() print(cars)
1 2 3 cars = ['bmw' , 'audi' , 'toyota' , 'subra' ] cars.sort(reverse=True ) print(cars)
不改变原来list的排序法:sorted
1 2 cars = ['bmw' , 'audi' , 'toyota' , 'subra' ] print(sorted(cars))
1 2 cars = ['bmw' , 'audi' , 'toyota' , 'subra' ] print(sorted(car,reverse=True ))
倒着打印列表
1 2 3 4 cars = ['bmw' ,'audi' ,'toyota' ,'subaru' ] print(cars) cars.reverse() print(cars)
列表长度
获取列表的长度: len(cars)
列表索引是从0开始的,在不为空的情况下可以使用 -1
表示访问最后一个元素
列表遍历
遍历列表,可以使用类似java的foreach语法
1 2 3 4 5 magicians = ['alice' , 'david' , 'carolina' ] for magician in magicians: print(magician.title() + ", that was great trick!" ) print("I can't wait to see your next trick, " + magician.title() + ".\n" ) print("Thank you everyone,that was a great magic show!" )
简单统计
对数字 列表元素惊醒简单地统计
1 2 3 digits = [1 , 2 , 4 , 0 , 10 , 8 , 7 , 9 ] print(str(digits) + "'s min:" + str(min(digits))+ " max:" + str(max(digits)) + " sum:" + str(sum(digits)))
切片操作
语法:var_list[start:end]
构建的列表元素属于 var_list[start],...,var_list[end-1]
说明:
var_list[:end]
:从头开始到end-1
var_list[start:]
:从start开始到len(var_list)-1
var_list[:]
:整个var_list
1 2 3 4 5 players = ['charles' , 'matina' , 'michael' , 'florence' , 'eli' ] print(players[0 :3 ]) print(players[:3 ]) print(players[:]) print(players[2 :])
应用:分页展示
元组
元组:不可变得列表;不能修改元组中的元素,但可以改变元组变量
使用园括号定义
使用下标或者foreach遍历元组
1 2 3 4 5 6 7 8 9 dimensions = (200 , 50 ) print(dimensions[0 ]) print(str(dimensions[1 ]) + "\n" ) for dimension in dimensions: print(dimension) dimensions = (400 , 100 ) print(dimensions)