Home  >  Article  >  Backend Development  >  python 切片和range()用法说明

python 切片和range()用法说明

WBOY
WBOYOriginal
2016-06-06 11:27:581453browse

理解切片基本用法:

首先需要明白,可迭代对象,按照正数索引(正序)是从0开始的,按照负数索引(逆序)是从-1开始的。
>>> astring = 'Hello world'
>>> astring[0:2]
'He'
>>>
可见,这种情况下,给切片操作一个起始位置,和一个终止位置,则显示从起始位置开始(包括起始位置)到终止位置(不包括终止位置)之间的内容;

在有负数索引的情况下,是类似的,只要确定终止位置的内容:

>>> astring[0:-1]
'Hello worl'
>>>

>>> astring
'Hello world'
>>> astring[0::1]
'Hello world'
>>> astring[0::2]
'Hlowrd'
>>> astring[0::3]
'Hlwl'
>>> astring[0::4]
'Hor'
>>>
在有三个参数的情况下,第一个起始位置,第二个是终止位置,地三个是步长。

测试程序:
# 首先理解切片含义,如下为切片程序结果演示
>>> s='abcde'
>>> s[:0]
''
>>> s[0:]
'abcde'
>>> s[1:]
'bcde'
>>> s[2:]
'cde'
>>> s[:3]
'abc'

理解range()基本用法:

测试程序一:

>>> range(1,5) # 输出从1到5的结果。包括头,不包括尾.
[1, 2, 3, 4]
>>> range(1,5,2) # 输出从1到5,间隔距离为2的结果。包括头,不包括尾.
[1, 3]
>>> range(5) # 输出从0到5的结果。默认起止为0。包括头,不包括尾.
[0, 1, 2, 3, 4]


测试程序二:

>>> s='abcde'
>>> i = -1
>>> for i in range(-1,-len(s),-1): # 输出结果
...     print s[:i]
...
abcd
abc
ab
a

测试程序三:

>>> s='abcde'
>>> for i in range(len(s),0,-1): # 输出结果
...     print s[:i]
...
abcde
abcd
abc
ab
a


测试程序四:

>>> s='abcde'
>>> for i in [None] + range(-1,-len(s),-1): # 用None作为索引值的输出结果
...     print s[:i]
...
abcde
abcd
abc
ab
a

另外,range可以直接给list变量赋值:
elements = range(0, 6)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn