Python---列表的学习(二)

列表的第二部分

(1)列表的排序

1)使用方法sort()可对列表进行永久性排序

food = ['apple','orange','pear','grape']
food.sort()
print(food)

看上面到结果,发现他是按照字典序排的

还可以按照字典序相反的方向排序

只需向sort()方法传递参数reverse = True

food = ['apple','orange','pear','grape']
food.sort()
print(food)
food.sort(reverse=True)
print(food)

2)使用sorted()方法对列表进行临时排序

food = ['apple','orange','pear','grape']
print(food)
print(sorted(food))
print(food)
print(sorted(food,reverse=True))
print(food)

从上面的例子可以看出这只是一个临时的排序,原本列表中的顺序并没有变,并且它也可以用reverse来传递参数

(2)倒着打印列表

food = ['apple','orange','pear','grape']
print(food)
food.reverse()
print(food)

reverse()是永久性修改列表的元素顺序的,但也可以恢复,怎么恢复就不说了

(3)列表的长度

food = ['apple','orange','pear','grape']
print(food)
print(len(food))

上面的方法就是得到列表的长度





posted @ 2018-04-27 12:15  lived  阅读(152)  评论(0)    收藏  举报