在Python中,代码不是越多越好,而是越少越好。代码不是越复杂越好,而是越简单越好。
List切片
>>> L = [‘Michael‘, ‘Sarah‘, ‘Tracy‘, ‘Bob‘, ‘Jack‘] >>> L[0:3] [‘Michael‘, ‘Sarah‘, ‘Tracy‘]#如果索引以0开始
>>> L[:3]
[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
倒切片
>>> L[-2:] #倒数几个就是负几 [‘Bob‘, ‘Jack‘] >>> L[-2:-1] [‘Bob‘]
例子:
1:遍历出1-100
>>> L = list(range(100))
2:取出1--10位,取多少位就是L[:10]
>>> L[:10] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3:取出后10位
>>> L[-10:] [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
4:取出11-20位
>>>L[10:20] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
5:前10个数,每5个取一个
>>>L[:10:2] #返回 [2,4,6,8]
6:所有数每5个取一个
>>>L[::5] [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
7:复制list
>>> L[:] [0, 1, 2, 3, ..., 99]
tuple切片
>>> (1,2,3,4,5,6)[:3] (1, 2, 3)
‘xxx‘也可以看做一种list
>>> ‘ABCDEFG‘[:3] ‘ABC‘ >>> ‘ABCDEFG‘[::2] ‘ACEG‘
时间: 2024-10-17 20:49:46