基本切片
对于任何可迭代的(例如,字符串,列表等),Python 允许你切片并返回其数据的子字符串或子列表。
切片格式:
iterable_name[start:stop:step]
哪里,
start
是切片的第一个索引。默认为 0(第一个元素的索引)stop
超过切片的最后一个索引。默认为 len(可迭代)step
是步长(下面的例子更好地解释)
例子:
a = "abcdef"
a # "abcdef"
# Same as a[:] or a[::] since it uses the defaults for all three indices
a[-1] # "f"
a[:] # "abcdef"
a[::] # "abcdef"
a[3:] # "def" (from index 3, to end(defaults to size of iterable))
a[:4] # "abcd" (from beginning(default 0) to position 4 (excluded))
a[2:4] # "cd" (from position 2, to position 4 (excluded))
此外,以上任何一种都可以与定义的步长一起使用:
a[::2] # "ace" (every 2nd element)
a[1:4:2] # "bd" (from index 1, to index 4 (excluded), every 2nd element)
指数可以是负数,在这种情况下,它们是从序列的末尾计算出来的
a[:-1] # "abcde" (from index 0 (default), to the second last element (last element - 1))
a[:-2] # "abcd" (from index 0 (default), to the third last element (last element -2))
a[-1:] # "f" (from the last element to the end (default len())
步长也可以是负数,在这种情况下,切片将以相反的顺序遍历列表:
a[3:1:-1] # "dc" (from index 2 to None (default), in reverse order)
此构造对于反转可迭代非常有用
a[::-1] # "fedcba" (from last element (default len()-1), to first, in reverse order(-1))
请注意,对于否定步骤,默认 end_index
是 None
(请参阅 http://stackoverflow.com/a/12521981 )
a[5:None:-1] # "fedcba" (this is equivalent to a[::-1])
a[5:0:-1] # "fedcb" (from the last element (index 5) to second element (index 1)