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']

  • 相关阅读:
    [转]命令行下常用网络命令解释大全
    查看计算机时间的命令行
    线程已被中止 “Thread was being aborted”
    SharePoint 2007备份还原小结
    作业
    .NET中线程同步相关的一些类
    SharePoint对于Workflow的历史信息清理的要点
    一些操作符
    for path多行变一列
    MERGE同步
  • 原文地址:https://www.cnblogs.com/myfy/p/11465684.html
Copyright © 2011-2022 走看看