python List

python List

最近用python刷leetcode, 经常用python中的列表,所以总结一下

以备不时之需

  • List 遍历

    List遍历有正序,逆序,跳跃式的遍历

    • 正序遍历
    example = [2, 1, 3, 4, 0]
    for i in range(len(example)):
        print example[i]
    
    
    #中途想改变i, 可以考虑while方式
    
    i = 0
    while i < len(example):
        print example[i]
        i += 1
    • 逆序遍历
    example = [2, 1, 3, 4, 0]
    for i in range(len(example))[::-1]:
        print example
    • 跳跃式遍历
    
    #步长为2
    
    example = [2, 1, 3, 4, 0]
    for i in range(len(example))[::2]:
        print example[i]
  • List排序,翻转

    List排序,翻转,需要注意原列表是否改变, 和排序,翻转操作函数是否返回值


    • 
      #sort 不返回值,原列表发生改变
      
      example=[2, 1, 3, 4, 0]
      example.sort()
      print example
      
      
      #sorted 返回值,但是原列表不变
      
      example = [2, 1, 3, 4, 0]
      exampleCopy = sorted(example)
      print example
      print exampleCopy
      
      
      #reverse 不返回值,原列表发生改变
      
      example = [2, 1, 3, 4, 0]
      example.reverse()
      print example
      
      
      #reversed 返回一个迭代器, 原列表不变
      
      example = [2, 1, 3, 4, 0]
      exampleCopy = reversed(example)
      print example
      print exampleCopy
  • List分片赋值

    List分片赋值,也是一个很强大的功能


    • example = [2, 1, 3, 4, 0]
      exampleOne = example[1 : 3]
      exampleTwo = example[:-2]
      exampleThree = example[::-1]
      
      #exampleOne = [1, 3]
      
      
      #exampleTwo = [2, 1, 3]
      
      
      #exampleThree = [0, 4, 3, 1, 2]
      
  • List pop方法

    List pop方法,可以用来实现栈


    • example = []
      example.append(2)
      example.append(1)
      example.append(3)
      example.append(4)
      example.append(0)
      while len(example) > 0:
          print example.pop()
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值