cars =['bmw','audi','toyota','subaru']print("\nHere is the original list:")print(cars)print("\nHere is the sorted list:")print(sorted(cars))#按字母顺序排序print("\nHere is the reverse sorted list:")print(sorted(cars, reverse =True))#按字母顺序逆排序print("\nHere is the original list again:")print(cars)#倒着打印列表
cars =['bmw','audi','toyota','subaru']
cars.reverse()#reverse永久性反转列表的排序print(cars)
3、操作列表
遍历整个列表
magicians =['alice','david','carolina']for magician in magicians:print(magician)
创建数字列表
#创建数字列表
numbers =list(range(1,6))#range(a,b)将生成[a,b)区间的数字print(numbers)
even_numbers =list(range(2,11,2))#range可指定每次增加的步长print(even_numbers)#例子:创建一个列表,其中包含前10个整数的平方
squares =[]for value inrange(1,11):
squares.append(value **2)print(squares)#对数字列表进行简单统计计算
digits =[1,2,3,4,5,6,7,8,9,0]print(min(digits))print(max(digits))print(sum(digits))#列表解析(简写方式生成列表)
squares =[value**2for value inrange(1,11)]print(squares)
使用列表的一部分/切片
players =['charles','martina','michaell','florence','eli']print(players[0:3])#指定索引列表[0,3)的元素print(players[:4])#指定索引列表[0,4)的元素print(players[2:])#指定索引列表[2,末尾)的元素print(players[-3:])#指定索引列表最后三个元素,负数索引返回离列表末尾相应距离的元素#遍历切片for player in players[:3]:print(player.title())