原创转载请注明出处:http://agilestyle.iteye.com/blog/2328911
- L = ['GuanYu', 'ZhangFei', 'ZhaoYun', 'MaChao', 'HuangZhong']
-
- # get the first 3 elements
- # ['GuanYu', 'ZhangFei', 'ZhaoYun']
- print(L[0:3])
- # ['GuanYu', 'ZhangFei', 'ZhaoYun']
- print(L[:3])
-
- # get the last 2 elements
- # ['MaChao', 'HuangZhong']
- print(L[-2:])
- # ['MaChao']
- print(L[-2:-1])
Console Output
Python支持L[-1]取倒数第一个元素, 记住倒数第一个元素的索引是-1
- L = list(range(100))
- # get the first 10 elements
- print(L[:10])
- # get the last 10 elements
- print(L[-10:])
- # get 11 - 20 elements
- print(L[10:20])
- # 前10个数,每2个取一个
- # [0, 2, 4, 6, 8]
- print(L[:10:2])
- # 所有数,每5个取一个
- # [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
- print(L[::5])
- # 只写[:]就可以原样复制一个list
- print(L[:])
Console Output
tuple也是一种list,唯一区别是tuple不可变
- t = (0, 1, 2, 3, 4, 5)[:3]
- # (0, 1, 2)
- print(t)
字符串'xxx'也可以看成是一种list,每个元素就是一个字符
- str1 = 'ABCDEFG'[:3]
- # ABC
- print(str1)
- # ACEG
- str2 = 'ABCDEFG'[::2]
- print(str2)
Console Output