最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

Python基础教程 序列共性详解

XAMPP案例 admin 582浏览 0评论

drr00067

说明:这里主要针对序列:字符串,列表,元组做介绍

序列索引

索引可以用来获取单一字符、列表元素、元组元素

索引示意图原理(以字符串为例)

+—+—+—+—+—+—+

| s | h | o | u | k | e |

+—+—+—+—+—+—+

0   1   2   3   4   5  6

-6  -5  -4  -3  -2  -1

非负数索引

字符串索引

>>> string = "python"
>>> string[0]  #character in position 0
'P'
>>> string[5]  #character in position 5
'n'

注意:第一个字符索引为0,依次类推,

列表索引

>>> list = [1, 4, 9, 16, 25] 
>>> list[0]  #返回索引为0的列表元素
1
>>> list[4]  #返回索引为4的列表元素
25

元组索引

>>> t = "i", "shou", "ke"
>>> t[0] #返回索引为0的元组元素
'i' 
>>> t[2] #返回索引为2的元组元素
'ke'

负数索引

字符串索引

>>> string = "python"
>>> string[-1]  # last character
'n'
>>> string[-2]  # second-last character
'o'
>>> string[-6]
'P'

注意:由于-0就是0,所以负数索引从-1开始,从右往左算

列表索引

>>> list = [1, 4, 9, 16, 25]
>>> list[-1] #返回最后一个列表元素
25
>>> list[-2] #返回倒数第二个列表元素
16

元组索引

>>> t = "i", "shou", "ke"
>>> t[-1] #返回最后一个元组元素
'ke'
>>> t[-2] #返回倒数第二个列表元素
'shou'

索引越界

索引越界出错

>>> string='shouke'
>>> string[7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

>>> list = [1, 2, 3]
>>> list[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

>>> tuple = (1, 2, 3)
>>> tuple[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

序列可为空

1.空字符串

>>> string =""
>>> string
''

2.空列表

>>> list = []
>>> list
[]

3.空元组

>>> tuple = ()
>>> tuple
()

序列切片

序列切片用于获取字符串、列表、元组

指定索引值

字符串切片

>>> prefix = 'ishouke'
>>> prefix[0:2] #索引值在0到2之间的字符(含索引为0的字符,但不含索引为2的字符)
'is'
>>> prefix[2:5]  #索引值在2到5之间的字符(含索引为2的字符,但不含索引为5的字符)
'hou'

说明:切片

[start:stop:step]

即:[开始索引:结束索引:步长值]

开始索引:从左倒右,从0开始,左边往右依次增大0,1,2……,值为负,从右往左,依次减小-1,-2……

结束索引:切片操作符将取到该索引为止,不包含该索引的值。

步长值:值为正,表示从左向右取,如果为负,则表示从右向左取。步长值不能为0,默认为1

例.取字符串中的最后三个字符

>>> str = 'mystring'
>>> str[:-4:-1]
'gni'

列表切片

>>> list = [1, 4, 9, 16, 25] 
>>> list[0:2]  #索引值在0到2之间的列表元素(不含索引为2的列表元素)
[1, 4]
>>> list[2:4]  #索引值在2到4之间的列表元素(不含索引为4的列表元素)
[9, 16]

说明:和字符串切片一样,不同的是这里返回的是列表

元组切片

>>> t = "i", "shou", "k", "e"
>>> t[0:2]  #索引值在0到2之间的元组元素(不含索引为2的元组元素)
('i', 'shou')
>>> t[2:3]  #索引值在2到3之间的元组元素(不含索引为3的元组元素)
('k',)

说明:和字符串切片一样,不同的是这里返回的是tuple元组

>>> t = 'i', 'shou', 'ke'
>>> t[:-1]  #注意,顺序是从左往右的
('i', 'shou')
>>> t[:]
('i', 'shou', 'ke')

采用默认索引值

字符串

>>> string = "shouke"
>>> string[:2]  #从索引为0到索引为1的所有字符
'sh' 
>>> string[4:]  #从索引为4的字符算起,往右的所有字符
'ke'
>>> string[-2:] # 倒数第二个字符(即索引值为-2的字符)开始,往右算起的所有字符
'ke'
>>> string[:] #返回整个字符串
'shouke'  # 注意:返回的是word的浅拷贝

注意:

切片仅含起始索引位置的字符,不含结束索引位置的字符,所以s[:i]+s[i:]总是等同s,如下:

>>> prefix[:2] + prefix[2:]
'ishouke'

列表

>>> list = [1, 4, 16, 25]
>>> list[:2] #从索引为0到索引为1的所有列表元素
[1, 4]
>>> list[2:]#从索引为2的元素算起,往右的所有元素
[1, 4]
>>> list[-2:]#倒数第二个元素(即索引值为-2的元素)开始,往右算起的所有元素
[16, 25]
>>> list[:]#所有列表元素
[1, 4, 16, 25]#注意,这里返回的是squares list的浅拷贝

元组

>>> tuple = (1, 4, 6, 5)
>>> tuple[:2]  #从索引为0到索引为1的所有元组元素
(1, 4)
>>> tuple[2:]  #从索引为2的元组元素算起,往右的所有元素
(6, 5)
>>> tuple[:]   #所有元组元素
(1, 4, 6, 5)

注意,引用切片,所指定的索引值越界不出错,如下


>>> string='shouke'
>>> string[4:42]
'ke'
>>> string[42:]
''

>>> list = [1, 2]
>>> list[4:]
[]

>>> tuple = (1, 2, 3)
>>> tuple[4:]
()

序列长度

len函数返回序列长度(字符串中字符个数,或者列表、元组中的元素个数)的大小

字符串

>>> string = "shouke"
>>> len(string)
6

>>> len("shouke")
6

列表

>>> list = ['s', 'h', 'o', 'u', 'k', 'e']
>>> len(list)
6
>>> len(['s', 'h', 'o', 'u', 'k', 'e'])
6

元组

>>> tuple = ('s', 'h', 'o', 'u', 'k', 'e')
>>> len(tuple)
6
>>> len(('s', 'h', 'o', 'u', 'k', 'e'))
6

序列的比较

字符串

>>> str1 = "shouke"
>>> str2 = "shouke"
>>> str1 == str2
True

>>> str1 = "abc"
>>> str2 = "abb"
>>> str3 = "Abc"
>>> str1 > str2
True
>>> str1 > str3
True

说明:

1.逐个比较相同索引上的字符,如果两字符的ASCII码值相同,则比较下一对字符,否则停止比较,如上,一直比较到索引为2的字符

2.ASCCI码较大的字符所在字符序列大于ASCII码值小的字符所在字符序列,如上,c的ASCII码大于b的ASCII码,所以str1 > str2

>>> str1 = "abcdefg"
>>> str2 = "abcdef"
>>> str3 = ""
>>> str1 > str2
True
>>> str3 < str2
True

说明:如果str2为str1的真子集,那么str1大于str2

列表

>>> list1 = [1, "str", 2]
>>> list2 = [1, "str", 2]
>>> list1 == list2
True

>>> ["i", "show", "ke"] > ["i", "shou", "ke"]
True

>>> [2,3] == [3,2]
False
>>> [2,3] == [2,3]
True

说明:

1.类似字符串,逐个比较列表相同索引元素的大小,如果当前两个元素相同则比较下一对元素,否则停止比较,列表中的元素

2.元素值较大的元素所在列表序列大于元素值较小的元素所在序列

>>> [1, 2, 3] < [1, 2, 3, 4]
True

说明:类似字符串,如果列表1是列表2的真子集,那么列表1小于列表2

元组

>>> tuple1 = (1, 2, 4)
>>> tuple2 = (1, 2, 4)
>>> tuple1 == tuple2
True

>>> (1, 2, 3) == (1.0, 2.0, 3.0)
True

>>> (1, 2 , 3) < (1, 2, 4)
True

>>> (1, 2, 3, 4) < (1, 2, 4)
True

>>> (1, 2) < (1, 2, -1)
True

说明:和列表一样

序列的连接

可用 + 号来连接序列

字符串

>>> string = "i"
>>> string + "shouke"
'ishouke'

>>> "i" + "shouke"
'ishouke'

列表

>>> list = ["i", "show"]
>>> list + ["k", "e"]
['i', 'show', 'k', 'e']

>>> ["i", "show"] +  ["k", "e"]
['i', 'show', 'k', 'e']

元组

>>> tuple = (1, 3, 3)
>>> tuple + (4, 5, 6)
(1, 3, 3, 4, 5, 6)

>>> (1, 3, 3) + (4, 5, 6)
(1, 3, 3, 4, 5, 6)

输出序列元素值

用print函数输出序列元素值

>>> string = "ishouke"
>>> print("one item of string: %s" % string[0])
one item of string: i

>>> list= ['i', 'shouke']
>>> print("one item of list filled with characters: %s" % list[0])
one item of list filled with characters: i

>>> tuple = ('i', 'shouke')
>>> print("one item of tuple filled with characters: %s" % tuple[0])
one item of tuple filled with characters: i

注意:仅在元素为字符串类型时才用 %s

使用*解引序列

*sequence 号可以解引数字,字符串,列表,元组等序列,但是不能单独使用

数字

>>> range = range(1, 4)
>>> print(*range)
1 2 3

字符串

>>> string = "shouke"
>>> print(*string)
s h o u k e # 注意,输出的字符串之间存在空格

列表

>>> list = ["i", "shou", "ke"]
>>> print(*list)
ishouke

元组

>>> tuple = ("i", "shou", "ke")
>>> print(*tuple)
ishouke

注意:不能单独使用,会报错如下

>>> range = range(1, 4)
>>> *range
  File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target

序列的遍历

可通过enumerate()同时接收位置索引和对应值

遍历单个序列

字符串

>>> for index, value in enumerate("ishouke"):
...     print(index, value)
...
0 i
1 s
2 h
3 o
4 u
5 k
6 e

列表

>>> for index, value in enumerate(['i', 'shou', 'ke']):
...     print(index, value)
...
0 i
1 shou
2 ke

元组

>>> for index, value in enumerate(("i", "shou", "ke")):
...     print(index, value)
...
0 i
1 shou
2 ke

同时遍历多个序列

同时遍历两个或更多序列,可使用zip()函数。

列表为例

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['shouke', 'holy grail', 'bule']
>>> for q, a in zip(questions, answers):
...     print('what is your {0}? It is {1}'.format(q, a))
...
what is your name? It is shouke
what is your quest? It is holy grail
what is your favorite color? It is bule

# {0},format函数中第一个参数,依次类推

注意:如果两个如果序列元素数目不一致,以更少的为准,如下

>>> ques = ['id', 'name', 'hobby']
>>> anser = ["tester", "shouke", "you guess", "other"]
>>> for q, a in zip(ques, anser):
...     print("what is your {0}?' it is {1}".format(q, a))
...
what is your id?' it is tester
what is your name?' it is shouke
what is your hobby?' it is you guess

一边遍历,一边修改序列

遍历期间,改变正在迭代的序列,建议先做个拷贝

列表为例

方法一:可使用切片隐式获取序列的拷贝

>>> words = ["i", "shou", "ke"]
#浅拷贝上迭代
>>> for w in words[:]:  # loop over a slice copy of the entire list
...     iflen(w) > 2:
...         words.insert(0, w)
...
>>> words
['shou', 'i', 'shou', 'ke']

方法二:使用显示的拷贝

注意:如果不做拷贝直接迭代,可能会有意想不到的结果,如下

>>> test_list = [1, 2, 3, 4, 5]
>>> for i in test_list:
	test_list.remove(i)
	print(i)

1
3
5

>>> test_list
[2, 4]

说明:每次执行remove(value),将移除list中第一个元素值为value的元素,同时,后面一个元素前移,补填到被删除元素的位置上

个人理解:应该是迭代器是按顺序取值的,如下,

首先迭代器定位在第1个元素,所以1可被移除

1 2 3 4 5

移除1后,第2,第3,……,第N个元素位置前移,迭代器定位在第2个位置的元素,所以3被删除

2 3 4 5

删除3后,第3,第4,……,第N个元素位置前移,迭代器定位在第3个位置的元素,所以5被移除

2 4 5

最后剩下 2, 4

解决方法:使用显示的拷贝

>>> test_list = [1, 2, 3, 4, 5]
>>> test_list_bak = [1, 2, 3, 4, 5]
>>> for w in test_list_bak:
...      test_list.remove(w)
...
>>>test_list
[]

翻转序列

reversed函数可用于逆转序列

a、数字序列

>>> for i in reversed(range(1, 5)):
...     print(i, end="")
...
4 3 2 1 >>>

b、字符串

>>> for i in reversed("ishouke"):
...     print(i, end="")
...
e k u o h s i >>>

c、列表

>>> for i in reversed(["shou", "ke", "i"]):
...     print(i, end="")
...
ikeshou>>>

d、元组

>>> for i in reversed(("sh", "ou", "ke", "i")):
...     print(i, end="")
...
ikeoush>>>

序列分解

1.字符串

>>> str = "is"
>>> x, y = str
>>> print(x, y)
i s

>>> x, y = "ab"
>>> print(x, y)
a b

2.列表

>>> x, y = ["i", "shou"]
>>> x
'i'
>>> y
'shou'
>>>

3.元组

>>> tuple = "i", "shou", "ke" #packing
>>> x, y, z = tuple  #unpacking
>>> x
'i'
>>> y
'shou'
>>> z
'ke'

注意:变量数和解压后的元素个数要对应,否则报错,如下

>>> x, y = "abc"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

转载请注明:XAMPP中文组官网 » Python基础教程 序列共性详解

您必须 登录 才能发表评论!