当前位置:   article > 正文

Python slice

python slice

原创转载请注明出处:http://agilestyle.iteye.com/blog/2328911

 

  1. L = ['GuanYu', 'ZhangFei', 'ZhaoYun', 'MaChao', 'HuangZhong']
  2. # get the first 3 elements
  3. # ['GuanYu', 'ZhangFei', 'ZhaoYun']
  4. print(L[0:3])
  5. # ['GuanYu', 'ZhangFei', 'ZhaoYun']
  6. print(L[:3])
  7. # get the last 2 elements
  8. # ['MaChao', 'HuangZhong']
  9. print(L[-2:])
  10. # ['MaChao']
  11. print(L[-2:-1])

Console Output

 

Python支持L[-1]取倒数第一个元素, 记住倒数第一个元素的索引是-1

  1. L = list(range(100))
  2. # get the first 10 elements
  3. print(L[:10])
  4. # get the last 10 elements
  5. print(L[-10:])
  6. # get 11 - 20 elements
  7. print(L[10:20])
  8. # 前10个数,每2个取一个
  9. # [0, 2, 4, 6, 8]
  10. print(L[:10:2])
  11. # 所有数,每5个取一个
  12. # [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
  13. print(L[::5])
  14. # 只写[:]就可以原样复制一个list
  15. print(L[:])

Console Output


 
tuple也是一种list,唯一区别是tuple不可变

  1. t = (0, 1, 2, 3, 4, 5)[:3]
  2. # (0, 1, 2)
  3. print(t)

字符串'xxx'也可以看成是一种list,每个元素就是一个字符

  1. str1 = 'ABCDEFG'[:3]
  2. # ABC
  3. print(str1)
  4. # ACEG
  5. str2 = 'ABCDEFG'[::2]
  6. print(str2)

Console Output


 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/611200
推荐阅读
相关标签
  

闽ICP备14008679号