{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 索引"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"对于<font color=Red>__元组、列表__</font>和<font color=Red>__range__</font> 对象等基本<font color=Red>__序列__</font>类型,序列中每个元素拥有一个序号。 \n",
"对于字符串,其中的每个字符拥有一个序号。 \n",
"序列数据内部的字符或元素按照顺序<font color=Red>__有序存储__</font>,可以使用序号取得相应的数据项或字符。\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python维护了两套索引: \n",
"<font color=Red>__正向索引__</font>正向从 <font color=Red>__0__</font> 开始,终止值为序列<font color=Red>__长度减1__</font>(元素个数减一,即 len(s)-1); \n",
"<font color=Red>__逆向索引__</font>从 <font color=Red>__-1__</font> 开始,逆向索引终止值为负的序列<font color=Red>__长度__</font>(即-len(s) ) \n",
"(注意,计算机中 -0 和 0 一样,因此,负数索引从 -1 开始)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"两种序号体系可以<font color=Red>__混合使用__</font>,并且结合两种表示方法可以方便的对序列进行索引和切片。 \n",
"图 6.1 中以列表和字符串为例给出正向和逆向两种索引编号规则的示例。 \n",
"对字符串而言,英文、中文、空格和各种符号都<font color=Red>__各占一个字符__</font>位。 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"对于序列结构数据来说,索引和步长都具有正负两个值,分别表示左、右两个方向取值。 \n",
"索引的正方向从左往右取值,起始位置为0; \n",
"逆向从右往左取值,起始位置为 -1。 \n",
"因此任意一个序列结构数据的索引范围为 -len(seq) 到 len(seq)-1 范围内的连续整数。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"images/ch5/1.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"所谓的<font color=Red>__索引__</font>是指通过序列数据的<font color=Red>__序号__</font>返回其对应的<font color=Red>__字符或元素__</font>的操作。 \n",
"可以按正向序号进行索引或按逆向序号进行索引,通过序号获取对应的元素。\n",
"索引的方法是:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"序列名<font color=Red>__[__</font>序号<font color=Red>__]__</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"images/ch5/2.png\">"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"H\n",
"H\n",
"o\n",
"o\n",
"P\n",
"P\n",
"!\n",
"!\n"
]
}
],
"source": [
"# 字符串序列\n",
"s = 'Hello Python!' # 字符串,13个字符,空格算字符\n",
"print(s[0]) # 按序号正向索引,返回序号为0的字符 'H'\n",
"print(s[-13]) # 按逆向序号索引,返回序号为-13的字符 'H'\n",
"\n",
"print(s[4]) # 按序号正向索引,返回序号为4的字符 'o'\n",
"print(s[-9]) # 按逆向序号索引,返回序号为-9的字符 'o'\n",
"\n",
"print(s[6]) # 按序号正向索引,返回序号为6的字符 'P'\n",
"print(s[-7]) # 按逆向序号索引,返回序号为-7的字符字符 'P'\n",
"\n",
"print(s[12]) # 按序号正向索引,返回序号为12的字符 '!'\n",
"print(s[-1]) # 按逆向序号索引,返回最后一个字符 '!'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 实例 6.1 从身份证获取性别"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"公民身份号码里面还隐含出生日期、出生地、性别等信息,身份证倒数第二位是性别信息,奇数表示“男”,偶数表示“女”。 \n",
"输入一个合法的身份证号,输出其持有者的性别。\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
" 1234564561451547165\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"性别为男\n"
]
}
],
"source": [
"id_number = input()\n",
"\n",
"if id_number[16] in '02468': # 字符串更简洁,也避免转整数的运算\n",
"# if int(id_number[16]) % 2 == 0: # 也可转整数再用取模运算判定奇偶\n",
" gender = '女'\n",
"else:\n",
" gender = '男'\n",
"\n",
"print(f'性别为{gender}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 利用条件表达式实现更简洁\n",
"\n",
"id_number = input()\n",
"gender = '女' if id_number[16] in '02468' else '男'\n",
"print(f'性别为{gender}')\n",
"\n",
"# 可在一行内完成\n",
"print(f'性别为女') if input()[16] in '02468' else print(f'性别为男')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"images/ch5/3.png\">"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"李明\n",
"88\n",
"55\n",
"85\n"
]
}
],
"source": [
"# 序列类型 — 列表\n",
"scores = ['李明', 84, 80, 95, 88, 76, 65, 85, 98, 55]\n",
"print(scores[0]) # 按序号正向索引,返回序号为0的元素'李明'\n",
"print(scores[4]) # 按序号正向索引,返回序号为3的元素88\n",
"print(scores[-1]) # 按逆向序号索引,返回倒数第1个元素55\n",
"print(scores[-3]) # 按逆向序号索引,返回倒数第3个元素85"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 序列类型 — range\n",
"r = range(10) # 获得0,1,2,3,4,5,6,7,8,9的序列对象\n",
"print(r[3]) # 按序号正向索引,返回序号为3的元素 3\n",
"print(r[-3]) # 按逆向序号索引,返回倒数第3个元素 7"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 索引超出范围"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"要注意的是,当使用的<font color=Red>__索引值超出__</font>列表现有数据的索引时,Python将会产生“索引超出范围”的错误。 \n",
"例如,用试图用scores[10] 或scores[-11]获取列表 scores中不存在的序号 10 的数据,会得到“<font color=Red>__IndexError: list index out of range__</font>”的出错提示。"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"ename": "IndexError",
"evalue": "list index out of range",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m/tmp/ipykernel_212/4158428604.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# 序列类型 — 列表索引越界\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mscores\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m'李明'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m84\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m80\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m95\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m88\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m76\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m65\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m85\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m98\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m55\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mscores\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;31m# 输出:IndexError: list index out of range\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mIndexError\u001b[0m: list index out of range"
]
}
],
"source": [
"# 序列类型 — 列表索引越界\n",
"scores = ['李明', 84, 80, 95, 88, 76, 65, 85, 98, 55]\n",
"print(scores[10])\n",
"# 输出:IndexError: list index out of range"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 序列类型 — 列表索引越界\n",
"scores = ['李明', 84, 80, 95, 88, 76, 65, 85, 98, 55]\n",
"print(scores[-11])\n",
"# 输出:IndexError: list index out of range"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 索引序号<font color=Red>__必须为整数__</font>,不可为浮点数。 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"当试图用浮点数做索引序号时,Python将会产生TypeError。 \n",
"当索引值是通过计算得到时,务必使其值为整型才可用做索引序号,或先对其进行<font color=Red>__取整操作__</font>再用做索引序号。 \n",
"例如,10 / 5和10.0 // 5的结果都为 2.0,这是一个浮点数,当尝试输出 scores 列表中索引号为 10 / 5的数据,因索引序号为浮点数,程序会返回“TypeError: list indices must be integers or slices, not float”的出错提示,提示用户“列表的索引必须是整数,不能是浮点数”。"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"80\n"
]
}
],
"source": [
"scores = ['李明', 84, 80, 95, 88, 76, 65, 85, 98, 55]\n",
"print(scores[10 / 5])\n",
"# 输出:TypeError: list indices must be integers or slices, not float"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 浮点数的整除结果是一个值等于整数的浮点数,也不可以做索引序号。"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"80\n"
]
}
],
"source": [
"scores = ['李明', 84, 80, 95, 88, 76, 65, 85, 98, 55]\n",
"print(10 // 5) # 运算结果为2.0,浮点数\n",
"print(scores[10 // 5])\n",
"# 输出:TypeError: list indices must be integers or slices, not float"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 以下用法可以得到整数,可用作序号\n",
"scores = ['李明', 84, 80, 95, 88, 76, 65, 85, 98, 55]\n",
"\n",
"print(scores[int(10 / 5)]) # 除法结果取整\n",
"print(scores[10 // 5]) # 整数做整除\n",
"print(scores[int(10.0 // 5)]) # 浮点数整除后取整\n",
"# 输出:TypeError: list indices must be integers or slices, not float"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 索引得到的对象的数据类型取决于序列中对应序号的元素的数据类型。 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" 如果索引结果仍是序列类型数据时,可以继续应用索引的方法获取元素中的数据。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cv = ['李明', 35, ('博士','副教授'), [96, 92, 85]] "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"列表 cv 中包含用3个逗号分隔开的4个元素,分别是: \n",
"字符串'李明'、整数 35, 元组('博士','副教授')和列表[96, 92, 85]。 "
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"李明\n",
"35\n",
"('博士', '副教授')\n",
"[96, 92, 85]\n"
]
}
],
"source": [
"cv = ['李明', 35, ('博士', '副教授'), [96, 92, 85]]\n",
"\n",
"# 包含字符串、数字、元组和列表等多种类型数据的列表\n",
"print(cv[0]) # 序号为 0 的元素为字符串:'李明'\n",
"print(cv[1]) # 序号为 1 的元素整数:35\n",
"print(cv[2]) # 序号为 2 的元素为元组('博士', '副教授')\n",
"print(cv[3]) # 序号为 3 的元素为列表[96, 92, 85]\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"其中包含的字符串'李明'、元组('博士','副教授')和列表[96, 92, 85]这三个元素都属于序列类型,可以继续应用索引的方法获取元素内部的数据。 \n",
"如:'李明'[0]的值为'李'、('博士','副教授')[1] 的值为'副教授'。"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"李明\n",
"李\n",
"('博士', '副教授')\n",
"[96, 92, 85]\n",
"博士\n",
"92\n"
]
}
],
"source": [
"cv = ['李明', 35, ('博士', '副教授'), [96, 92, 85]]\n",
"# 包含字符串、数字、元组和列表等多种类型数据的列表\n",
"print(cv[0]) # 序号为 0 的元素为字符串:'李明'\n",
"print(cv[0][0]) # 序号为 0 的元素中序号为0的元素为:'李'\n",
"print(cv[2]) # 序号为 2 的元素为元组('博士', '副教授')\n",
"print(cv[3]) # 序号为 3 的元素为列表[96, 92, 85]\n",
"print(cv[2][0]) # 序号为 2 的元素中序号为0的元素为:博士\n",
"print(cv[3][1]) # 序号为 3 的元素中序号为1的元素为:92\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"cv[2] 索引的结果是一个元组:('博士', '副教授'),元组仍是一个序列类型数据,仍可应用索引获取其中的元素。 \n",
"cv[2][0]相当于:('博士', '副教授')[0] \n",
"元组对象('博士', '副教授')中序号为0的元素为:’博士’ \n",
"所以cv[2][0]最终获取的数据为:'博士'。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 实例 6.2 百分制转五分制 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"可以用字符串索引的方法实现百分制成绩转五分制成绩。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"先将 区间0-100 划分为[0,10)、[10,20)、[20,30)、[30,40)、[40,50)、[50,60)、[60,70)、[70,80)、[80,90)、[90,100)、[100] 共 11 个区间。 \n",
"各区间成绩分别对应五分制的“E、E、E、E、E、E、D、C、B、A、A”。 \n",
"如果将落在各区间的数分别对 10 做整除,正好可以得到 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10共 10 个数字。 \n",
"这些数字正好是字符串“EEEEEEDCBAA”中每个字符的序号。 \n",
"根据用户输入的分数整除10,去掉其个位上的数字,得到其十位上的数字“i”,字符串中以“i”值作为索引的字符正好对应该分数段的五分制成绩。 \n",
"例如,输入85时,85//10 的结果为 8,输出字符串中序号为 8 的字符“B”。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"score = int(input()) # 输入整数\n",
"degree = 'EEEEEEDCBAA' # 序号0,1,2,3,4,5,6,7,8,9,10\n",
"if score > 100 or score < 0: # 排除不合法数据\n",
" print('Data error!')\n",
"else:\n",
" i = score // 10\n",
" print(degree[i]) # degree[i]索引返回其中序号为i的字符"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"以上程序也可以用条件表达式实现:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"score = int(input())\n",
"degree = 'EEEEEEDCBAA'\n",
"print('Data error!') if (score > 100 or score < 0) else print(degree[score // 10])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font face='楷体' color='red' size=5> 练一练1 </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"实例6.2的程序要求输入必须为整数,否则会触发异常。修改这个程序,使之可以接收浮点数的输入并正确转为五分制输出。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 补充你的程序\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"测试用例:\n",
"输入:\n",
"99.9\n",
"输出:\n",
"A"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font face='楷体' color='red' size=5> 练一练2 </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"继续修改这个程序,使之可以重复接收浮点数的输入并正确转为五分制输出,直到输入回车时结束程序。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 补充你的程序\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"测试用例:\n",
"101.5\n",
"Data error!\n",
"100\n",
"A\n",
"59.9\n",
"E\n",
"88\n",
"B\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}