zoukankan      html  css  js  c++  java
  • 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']

  • 相关阅读:
    Spring-Cloud 学习笔记-(4)负载均衡器Ribbon
    Spring-Cloud 学习笔记-(5)熔断器Hystrix
    微信支付(APP)
    Resetting Frame Animation
    Java内部类与final关键字详解
    UML中关联(Association)和依赖(Dependency)的区别
    ListView 介绍
    android Activity类中的finish()、onDestory()和System.exit(0) 三者的区别
    AsyncTask和Handler对比
    create groups 和 create folder reference
  • 原文地址:https://www.cnblogs.com/myfy/p/11465684.html
Copyright © 2011-2022 走看看