• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Lucky
博客园    首页    新随笔    联系   管理    订阅  订阅

Python_列表操作2

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

colorsList=['hong','cheng','huang','lv']

colorsList.sort() #正序排序
print(colorsList)

colorsList.sort(reverse=True) #倒序 关键字:reverse=True
print(colorsList)

执行结果:

['cheng', 'hong', 'huang', 'lv']
['lv', 'huang', 'hong', 'cheng']

 

2.使用函数sorted()对列表进行临时排序:(sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。)

print('原列表:')
print(colorsList)

print('调用sorted()方法升序后的临时列表:')
print(sorted(colorsList)) #升序

print('调用sorted()方法后的原列表:')
print(colorsList)


print('原列表:')
print(colorsList)

print('调用sorted()方法倒序后的临时列表:')
print(sorted(colorsList,reverse=True)) #倒序

print('调用sorted()方法后的原列表:')
print(colorsList)

 

执行结果:

原列表:
['hong', 'cheng', 'huang', 'lv']
调用sorted()方法升序后的临时列表:
['cheng', 'hong', 'huang', 'lv']
调用sorted()方法后的原列表:
['hong', 'cheng', 'huang', 'lv']
原列表:
['hong', 'cheng', 'huang', 'lv']
调用sorted()方法倒序后的临时列表:
['lv', 'huang', 'hong', 'cheng']
调用sorted()方法后的原列表:
['hong', 'cheng', 'huang', 'lv']

 

3.reverse()方法:反转列表元素的排列顺序

colorsList=['hong','cheng','huang','lv']

print('原列表:')
print(colorsList)

colorsList.reverse()
print('调用reverse()方法第一次反转后的列表:')
print(colorsList) #第一次反转

colorsList.reverse()
print('调用reverse()方法第二次反转后的列表:')
print(colorsList) #第二次反转

执行结果:

原列表:
['hong', 'cheng', 'huang', 'lv']
调用reverse()方法第一次反转后的列表:
['lv', 'huang', 'cheng', 'hong']
调用reverse()方法第二次反转后的列表:
['hong', 'cheng', 'huang', 'lv']

 

posted @ 2019-09-05 14:13  半仙儿~~~  阅读(185)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3