当前位置 : 主页 > 编程语言 > python >

Python高级变量类型

来源:互联网 收集:自由互联 发布时间:2022-07-05
仅用学习参考 目标 列表 元组 字典 字符串 公共方法 变量高级 知识点回顾 Python 中数据类型可以分为数字型和非数字型 数字型 整型 (​​int​​) 浮点型(​​float​​) 布尔型(​​

仅用学习参考


Python高级变量类型_python


目标

  • 列表
  • 元组
  • 字典
  • 字符串
  • 公共方法
  • 变量高级

知识点回顾

  • Python 中数据类型可以分为数字型和非数字型
  • 数字型
  • 整型 (​​int​​)
  • 浮点型(​​float​​)
  • 布尔型(​​bool​​)
  • 真​​True​​​​非 0 数​​ ——非零即真
  • 假​​False​​​​0​​
  • 复数型 (​​complex​​)
  • 主要用于科学计算,例如:平面场问题、波动问题、电感电容等问题

  • 非数字型
  • 字符串
  • 列表
  • 元组
  • 字典
  • 在​​Python​​ 中,所有非数字型变量都支持以下特点:
  • 都是一个序列​​sequence​​,也可以理解为容器
  • 取值​​[]​​
  • 遍历​​for in​​
  • 计算长度、最大/最小值、比较、删除
  • 链接​​+​​ 和重复​​*​​
  • 切片

    01. 列表

    1.1 列表的定义

    • ​​List​​​(列表) 是 ​​Python​​ 中使用 最频繁 的数据类型,在其他语言中通常叫做 数组
    • 专门用于存储一串 信息
    • 列表用​​[]​​ 定义,数据 之间使用 ​​,​​ 分隔
    • 列表的索引 从 ​​0​​ 开始
    • 索引就是数据在列表中的位置编号,索引又可以被称为下标

    注意:从列表中取值时,如果 超出索引范围,程序会报错

    In [33]: smoke_list = ["蓝利群", "芙蓉王", "万宝路"]

    In [34]: for smoke in smoke_list:
    ...: print smoke
    ...:
    蓝利群
    芙蓉王
    万宝路

    In [35]:

    In [35]: print smoke_list[0]
    蓝利群

    In [36]: print smoke_list[1]
    芙蓉王

    In [37]: print smoke_list[2]
    万宝路

    In [38]: print smoke_list[3]
    ---------------------------------------------------------------------------
    IndexError Traceback (most recent call last)
    <ipython-input-38-53890986dcdc> in <module>()
    ----> 1 print smoke_list[3]

    IndexError: list index out of range

    In [39]:


    Python高级变量类型_python_02


    按照图片的函数执行一下看看:

    In [40]: len(smoke_list)
    Out[40]: 3

    In [41]: smoke_list.count("蓝利群")
    Out[41]: 1

    In [42]:

    In [44]: smoke_list.sort()

    In [45]: for smoke in smoke_list:
    ...: print smoke
    ...:
    万宝路
    芙蓉王
    蓝利群

    In [46]:

    In [46]: smoke_list.sort(reverse=True)

    In [47]: for smoke in smoke_list:
    ...: print smoke
    ...:
    蓝利群
    芙蓉王
    万宝路

    In [48]:

    In [48]: smoke_list.reverse()

    In [49]: for smoke in smoke_list:
    ...: print smoke
    ...:
    万宝路
    芙蓉王
    蓝利群

    In [50]:

    In [50]: smoke_list.insert(1,"黄金龙")

    In [51]: for smoke in smoke_list:
    ...: print smoke
    ...:
    万宝路
    黄金龙
    芙蓉王
    蓝利群

    In [52]:

    In [52]: smoke_list.append("王者农药")

    In [53]: for smoke in smoke_list:
    ...: print smoke
    ...:
    万宝路
    黄金龙
    芙蓉王
    蓝利群
    王者农药

    In [54]:

    In [54]: smoke_list2 = ["胖哥槟榔"]

    In [55]: smoke_list.extend(smoke_list2)

    In [56]: for smoke in smoke_list:
    ...: print smoke
    ...:
    万宝路
    黄金龙
    芙蓉王
    蓝利群
    王者农药
    胖哥槟榔

    In [57]:

    In [57]: del smoke_list[1]

    In [58]: for smoke in smoke_list:
    ...: print smoke
    ...:
    万宝路
    芙蓉王
    蓝利群
    王者农药
    胖哥槟榔

    In [59]:

    In [61]: smoke_list.remove("蓝利群")

    In [62]: for smoke in smoke_list:
    ...: print smoke
    ...:
    万宝路
    芙蓉王
    王者农药
    胖哥槟榔

    In [63]:

    In [63]: smoke_list.pop()
    Out[63]: '\xe8\x83\x96\xe5\x93\xa5\xe6\xa7\x9f\xe6\xa6\x
    94'

    In [64]: smoke_list.pop
    Out[64]: <function pop>

    In [65]: smoke_list.pop()
    Out[65]: '\xe7\x8e\x8b\xe8\x80\x85\xe5\x86\x9c\xe8\x8d\x
    af'

    In [66]: for smoke in smoke_list:
    ...: print smoke
    ...:
    万宝路
    芙蓉王

    In [67]: smoke_list.pop(0)
    Out[67]: '\xe4\xb8\x87\xe5\xae\x9d\xe8\xb7\xaf'

    In [68]: for smoke in smoke_list:
    ...: print smoke
    ...:
    芙蓉王

    In [69]:

    02. 元组

    2.1 元组的定义

    • ​​Tuple​​(元组)与列表类似,不同之处在于元组的元素不能修改
    • 元组表示多个元素组成的序列
    • 元组在​​Python​​ 开发中,有特定的应用场景
    • 用于存储一串 信息,数据之间使用​​,​​ 分隔
    • 元组用​​()​​ 定义
    • 元组的索引从​​0​​ 开始
    • 索引就是数据在元组中的位置编号

    In [69]: smoke_tuple = ("蓝利群","万宝路","芙蓉王")

    In [70]: print smoke_tuple
    ('\xe8\x93\x9d\xe5\x88\xa9\xe7\xbe\xa4', '\xe4\xb8\x87\x
    e5\xae\x9d\xe8\xb7\xaf', '\xe8\x8a\x99\xe8\x93\x89\xe7\x
    8e\x8b')

    创建空元组

    smoke_tuple = ()

    元组中 只包含一个元素 时,需要 在元素后面添加逗号

    smoke_tuple = ("蓝利群", )


    Python高级变量类型_python_03


    In [71]: len(smoke_tuple)
    Out[71]: 3

    In [73]: smoke_tuple.count("蓝利群")
    Out[73]: 1

    In [73]: smoke_tuple.count("蓝利群")
    Out[73]: 1

    In [74]: print smoke_tuple[0]
    蓝利群

    In [75]: print smoke_tuple.index("万宝路")
    1

    In [76]:

    In [76]: for smoke in smoke_tuple:
    ...: print smoke
    ...:
    蓝利群
    万宝路
    芙蓉王

    In [77]:

    元组和列表之间的转换

    • 使用​​list​​ 函数可以把元组转换成列表
    list(元组)

    In [80]: type(smoke_tuple)
    Out[80]: tuple

    In [81]: smoke_tuple = list(smoke_tuple)

    In [82]: type(smoke_tuple)
    Out[82]: list
    • 使用​​tuple​​ 函数可以把列表转换成元组
    tuple(列表)

    In [83]: type(smoke_tuple)
    Out[83]: list

    In [84]: smoke_tuple = tuple(smoke_tuple)

    In [85]: type(smoke_tuple)
    Out[85]: tuple

    03. 字典

    3.1 字典的定义

    • ​​dictionary​​(字典) 是 除列表以外 ​​Python​​ 之中 最灵活 的数据类型
    • 字典同样可以用来存储多个数据
    • 通常用于存储描述一个 ​​物体​​ 的相关信息
    • 和列表的区别
    • 列表 是 有序 的对象集合
    • 字典 是 无序 的对象集合
    • 字典用​​{}​​ 定义
    • 字典使用键值对 存储数据,键值对之间使用 ​​,​​ 分隔
    • 键 ​​key​​ 是索引
    • 值 ​​value​​ 是数据
    • 键 和 值 之间使用 ​​:​​ 分隔
    • 键必须是唯一的
    • 值 可以取任何数据类型,但 键 只能使用 字符串、数字或 元组

    In [87]: smoke_dict = {"蓝利群":17.5,"万宝路":18,"芙蓉
    ...: 王":26}

    In [88]: print smoke_dict
    {'\xe8\x8a\x99\xe8\x93\x89\xe7\x8e\x8b': 26, '\xe4\xb8\x
    87\xe5\xae\x9d\xe8\xb7\xaf': 18, '\xe8\x93\x9d\xe5\x88\x
    a9\xe7\xbe\xa4': 17.5}


    Python高级变量类型_python_04


    In [89]: len(smoke_dict)
    Out[89]: 3

    In [90]: print smoke_dict[4]
    --------------------------------------------------------

    KeyError Traceback (most recent call last)
    <ipython-input-90-9a992459c2af> in <module>()
    ----> 1 print smoke_dict[4]

    KeyError: 4

    In [91]: print smoke_dict.get(4)
    None

    In [92]:

    In [93]: for key in smoke_dict:
    ...: print("key = %s, value = %s " % (key,smoke_dict[key]))
    ...:
    ...:
    key = 芙蓉王, value = 26
    key = 万宝路, value = 18
    key = 蓝利群, value = 17.5

    04. 字符串

    4.1 字符串的定义

    • 字符串就是一串字符,是编程语言中表示文本的数据类型
    • 在 Python 中可以使用一对双引号​​"​​ 或者一对单引号​​'​​ 定义一个字符串
    • 虽然可以使用​​\"​​​ 或者​​\'​​ 做字符串的转义,但是在实际开发中:
    • 如果字符串内部需要使用​​"​​​,可以使用​​'​​ 定义字符串
    • 如果字符串内部需要使用​​'​​​,可以使用​​"​​ 定义字符串
    • 可以使用索引获取一个字符串中指定位置的字符,索引计数从0开始
    • 也可以使用​​for​​循环遍历字符串中每一个字符

    大多数编程语言都是用 ​​"​​ 来定义字符串

    In [94]: string = "Hello Python"
    ...:
    ...: for c in string:
    ...: print(c)
    ...:
    H
    e
    l
    l
    o

    P
    y
    t
    h
    o
    n

    In [95]:

    In [95]: string = "胖子老板,吃饭了没有呀"
    ...:
    ...: for c in string:
    ...: print(c)
    ...:




    In [96]:


    Python高级变量类型_元组_05


    In [96]: string1 = "hello fat boss"

    In [97]: len(string1)
    Out[97]: 14

    In [98]: string1.count("l")
    Out[98]: 2

    In [99]: string1[0]
    Out[99]: 'h'

    In [100]: string1.index("l")
    Out[100]: 2

    In [101]:

    4.2 字符串的常用操作

    • 在​​ipython3​​ 中定义一个字符串,例如:​​hello_str = ""​​
    • 输入​​hello_str.​​​ 按下​​TAB​​​ 键,​​ipython​​ 会提示字符串能够使用的方法如下:
    In [1]: hello_str.
    hello_str.capitalize hello_str.isidentifier hello_str.rindex
    hello_str.casefold hello_str.islower hello_str.rjust
    hello_str.center hello_str.isnumeric hello_str.rpartition
    hello_str.count hello_str.isprintable hello_str.rsplit
    hello_str.encode hello_str.isspace hello_str.rstrip
    hello_str.endswith hello_str.istitle hello_str.split
    hello_str.expandtabs hello_str.isupper hello_str.splitlines
    hello_str.find hello_str.join hello_str.startswith
    hello_str.format hello_str.ljust hello_str.strip
    hello_str.format_map hello_str.lower hello_str.swapcase
    hello_str.index hello_str.lstrip hello_str.title
    hello_str.isalnum hello_str.maketrans hello_str.translate
    hello_str.isalpha hello_str.partition hello_str.upper
    hello_str.isdecimal hello_str.replace hello_str.zfill
    hello_str.isdigit hello_str.rfind

    提示:正是因为 python 内置提供的方法足够多,才使得在开发时,能够针对字符串进行更加灵活的操作!应对更多的开发需求!

    1) 判断类型 - 9

    方法

    说明

    string.isspace()

    如果 string 中只包含空格,则返回 True

    string.isalnum()

    如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True

    string.isalpha()

    如果 string 至少有一个字符并且所有字符都是字母则返回 True

    string.isdecimal()

    如果 string 只包含数字则返回 True,​​全角数字​​

    string.isdigit()

    如果 string 只包含数字则返回 True,​​全角数字​​​、​​⑴​​​、​​\u00b2​​

    string.isnumeric()

    如果 string 只包含数字则返回 True,​​全角数字​​​,​​汉字数字​​

    string.istitle()

    如果 string 是标题化的(每个单词的首字母大写)则返回 True

    string.islower()

    如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True

    string.isupper()

    如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True

    2) 查找和替换 - 7

    方法

    说明

    string.startswith(str)

    检查字符串是否是以 str 开头,是则返回 True

    string.endswith(str)

    检查字符串是否是以 str 结束,是则返回 True

    string.find(str, start=0, end=len(string))

    检测 str 是否包含在 string 中,如果 start 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回 ​​-1​​

    string.rfind(str, start=0, end=len(string))

    类似于 find(),不过是从右边开始查找

    string.index(str, start=0, end=len(string))

    跟 find() 方法类似,不过如果 str 不在 string 会报错

    string.rindex(str, start=0, end=len(string))

    类似于 index(),不过是从右边开始

    string.replace(old_str, new_str, num=string.count(old))

    把 string 中的 old_str 替换成 new_str,如果 num 指定,则替换不超过 num 次

    3) 大小写转换 - 5

    方法

    说明

    string.capitalize()

    把字符串的第一个字符大写

    string.title()

    把字符串的每个单词首字母大写

    string.lower()

    转换 string 中所有大写字符为小写

    string.upper()

    转换 string 中的小写字母为大写

    string.swapcase()

    翻转 string 中的大小写

    4) 文本对齐 - 3

    方法

    说明

    string.ljust(width)

    返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

    string.rjust(width)

    返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串

    string.center(width)

    返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

    5) 去除空白字符 - 3

    方法

    说明

    string.lstrip()

    截掉 string 左边(开始)的空白字符

    string.rstrip()

    截掉 string 右边(末尾)的空白字符

    string.strip()

    截掉 string 左右两边的空白字符

    6) 拆分和连接 - 5

    方法

    说明

    string.partition(str)

    把字符串 string 分成一个 3 元素的元组 (str前面, str, str后面)

    string.rpartition(str)

    类似于 partition() 方法,不过是从右边开始查找

    string.split(str="", num)

    以 str 为分隔符拆分 string,如果 num 有指定值,则仅分隔 num + 1 个子字符串,str 默认包含 '\r', '\t', '\n' 和空格

    string.splitlines()

    按照行('\r', '\n', '\r\n')分隔,返回一个包含各行作为元素的列表

    string.join(seq)

    以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串

    4.3 字符串的切片

    • 切片方法适用于字符串、列表、元组
    • 切片使用索引值来限定范围,从一个大的字符串中切出小的字符串
    • 列表和元组都是有序的集合,都能够通过索引值获取到对应的数据
    • 字典是一个无序的集合,是使用键值对保存数据
      Python高级变量类型_字符串_06
    字符串[开始索引:结束索引:步长]

    In [102]: string2 = string1[0:3:1]

    In [103]: print string2
    hel

    In [104]: print string1[1:3:2]
    e

    In [105]:

    注意:

  • 指定的区间属于左闭右开型​​[开始索引, 结束索引)​​​ =>​​开始索引 >= 范围 < 结束索引​​
    • 从​​起始​​ 位开始,到​​结束​​位的前一位结束(不包含结束位本身)
  • 从头开始,开始索引数字可以省略,冒号不能省略
  • 到末尾结束,结束索引数字可以省略,冒号不能省略
  • 步长默认为​​1​​,如果连续切片,数字和冒号都可以省略
  • 索引的顺序和倒序

    • 在 Python 中不仅支持顺序索引,同时还支持倒序索引
    • 所谓倒序索引就是从右向左计算索引
    • 最右边的索引值是-1,依次递减

    演练需求

  • 截取从 2 ~ 5 位置 的字符串
  • 截取从 2 ~​​末尾​​ 的字符串
  • 截取从​​开始​​ ~ 5 位置 的字符串
  • 截取完整的字符串
  • 从开始位置,每隔一个字符截取字符串
  • 从索引 1 开始,每隔一个取一个
  • 截取从 2 ~​​末尾 - 1​​ 的字符串
  • 截取字符串末尾两个字符
  • 字符串的逆序(面试题)

    答案

    num_str = "0123456789"

    # 1. 截取从 2 ~ 5 位置 的字符串
    print(num_str[2:6])

    # 2. 截取从 2 ~ `末尾` 的字符串
    print(num_str[2:])

    # 3. 截取从 `开始` ~ 5 位置 的字符串
    print(num_str[:6])

    # 4. 截取完整的字符串
    print(num_str[:])

    # 5. 从开始位置,每隔一个字符截取字符串
    print(num_str[::2])

    # 6. 从索引 1 开始,每隔一个取一个
    print(num_str[1::2])

    # 倒序切片
    # -1 表示倒数第一个字符
    print(num_str[-1])

    # 7. 截取从 2 ~ `末尾 - 1` 的字符串
    print(num_str[2:-1])

    # 8. 截取字符串末尾两个字符
    print(num_str[-2:])

    # 9. 字符串的逆序(面试题)
    print(num_str[::-1])

    05. 公共方法

    5.1 Python 内置函数

    Python 包含了以下内置函数:

    函数

    描述

    备注

    len(item)

    计算容器中元素个数

    del(item)

    删除变量

    del 有两种方式

    max(item)

    返回容器中元素最大值

    如果是字典,只针对 key 比较

    min(item)

    返回容器中元素最小值

    如果是字典,只针对 key 比较

    cmp(item1, item2)

    比较两个值,-1 小于/0 相等/1 大于

    Python 3.x 取消了 cmp 函数

    注意

    • 字符串比较符合以下规则: "0" < "A" < "a"

    5.2 切片

    描述

    Python 表达式

    结果

    支持的数据类型

    切片

    "0123456789"[::-2]

    "97531"

    字符串、列表、元组

    • 切片使用索引值来限定范围,从一个大的字符串中切出小的字符串
    • 列表和元组都是有序的集合,都能够通过索引值获取到对应的数据
    • 字典是一个无序的集合,是使用键值对保存数据

    5.3 运算符

    运算符

    Python 表达式

    结果

    描述

    支持的数据类型

    +

    [1, 2] + [3, 4]

    [1, 2, 3, 4]

    合并

    字符串、列表、元组

    *

    ["Hi!"] * 4

    ['Hi!', 'Hi!', 'Hi!', 'Hi!']

    重复

    字符串、列表、元组

    in

    3 in (1, 2, 3)

    True

    元素是否存在

    字符串、列表、元组、字典

    not in

    4 not in (1, 2, 3)

    True

    元素是否不存在

    字符串、列表、元组、字典

    > >= == < <=

    (1, 2, 3) < (2, 2, 3)

    True

    元素比较

    字符串、列表、元组

    注意

    • ​​in​​ 在对字典操作时,判断的是字典的键
    • ​​in​​​ 和​​not in​​ 被称为成员运算符

    成员运算符

    成员运算符用于 测试 序列中是否包含指定的 成员

    运算符

    描述

    实例

    in

    如果在指定的序列中找到值返回 True,否则返回 False

    ​​3 in (1, 2, 3)​​​ 返回 ​​True​​

    not in

    如果在指定的序列中没有找到值返回 True,否则返回 False

    ​​3 not in (1, 2, 3)​​​ 返回 ​​False​​

    注意:在对 字典 操作时,判断的是 字典的键

    5.4 完整的 for 循环语法

    • 在​​Python​​​ 中完整的​​for 循环​​ 的语法如下:
    for 变量 in 集合:

    循环体代码
    else:
    没有通过 break 退出循环,循环结束后,会执行的代码

    应用场景

    • 在迭代遍历嵌套的数据类型时,例如一个列表包含了多个字典
    • 需求:要判断 某一个字典中 是否存在 指定的 值
    • 如果存在,提示并且退出循环
    • 如果不存在,在循环整体结束后,希望得到一个统一的提示

    students = [
    {"name": "阿土",
    "age": 20,
    "gender": True,
    "height": 1.7,
    "weight": 75.0},
    {"name": "小美",
    "age": 19,
    "gender": False,
    "height": 1.6,
    "weight": 45.0},
    ]

    find_name = "阿土"

    for stu_dict in students:

    print(stu_dict)

    # 判断当前遍历的字典中姓名是否为find_name
    if stu_dict["name"] == find_name:
    print("找到了")

    # 如果已经找到,直接退出循环,就不需要再对后续的数据进行比较
    break

    else:
    print("没有找到")

    print("循环结束")


    Python高级变量类型_字符串_07



    关注微信公众号,回复【资料】、Python、PHP、JAVA、web,则可获得Python、PHP、JAVA、前端等视频资料。


    上一篇:Python 多任务介绍
    下一篇:没有了
    网友评论