Python study 笔记

81 阅读8分钟

list 方法

  • append(value) list尾部添加 value

  • pop(index) 选填接收参数,不填默认删除list最后一个,可删除指定的下标

  • insert(index,obj)
    index 插入位置的下标,
    obj 需要插入的obj

  • extend(seq) 在当前元素末尾追加另一个list的值

  • clear() 清空列表数据

  • len(obj) 统计 list 中有多少个元素

  • count(value) 统计 list 中指定 value 出现的次数

格式写法

  • %s 打印字符串
# 打印字符串
str1 = "这是一个字符串"
print("打印字符串:%s " % str1)

结果

image.png

  • %d 打印整数
# 打印整数
number = 123456
print('打印数值:%d' % number)

结果

image.png

  • %f 打印浮点数 保留几位小数 %0.2f
# 打印浮点数
f_numb = 6.5
print("打印浮点数:%f" % f_numb)

# 保留两位小数
print("打印浮点数:%0.2f" % f_numb)

结果

image.png

循环遍历 iteration

name_list = ["张三", "李四", "王二", "张", "张三", "张三", "张三", ]
# 循环遍历  iteration
for name in name_list:
    print("打印值:%s" % name)

image.png

tuple (元组)的使用

  • 定义tuple
empty_tuple = ()
print("数据类型:", type(empty_tuple))     # <class 'tuple'>
  • 一个 tuple 里包含 multiple elements (多个元素)
many_tuple = ("张三", 18, 456.5)

# 通过下标获取 value
print(many_tuple[0])    # 张三
print(many_tuple[2])    # 456.5
  • 当 tuple 中包含一个 value时,python 会忽略括号,直接读取 元组中的值 解释器为 int ,需要加, 才能解读为 tuple
one_tuple = (6,)
print("一个值时的tuple类型:", type(one_tuple))     # 一个值时的tuple类型: <class 'tuple'>
  • tuple 类型里的元素不支持修改
info = (18, 20, 66, "你好")
info[0] = 10            # 无效
print(info)     # (18, 20, 66, '你好')

结果

image.png

  • 统计元组 value 的数量 len 函数
info = (18, 20, 66, "你好", 18, 20, 100, "Hello world")
print(" 打印 tuple 中 value 的length:", len(info))    # 8
  • 因为 元组中可以同时定义,string, int, float,在实际开发中就很难确定元组中的数据类型,所以针对元组的循环遍历需求并不是很多
info = (18, 20, 66, "你好", 18, 20, 100, "Hello world")
for name_info in info:
    print(name_info)

结果

image.png

  • 元组和列表之间的转换

应用场景:
如果不想 list 被修改 ,就通过 tuple 函数把 list 转换成 tuple 类型
如果想修改 tuple 中的 value , 就通过 list 函数把 tuple 转换成 list 类型

num_list = [20, 100, 16]
print(type(num_list))   # <class 'list'>

# tuple 函数把 num_list 转换成 tuple
tuple_list = tuple(num_list)
print(type(tuple_list))     # <class 'tuple'>

# list 函数把 tuple_list 转换成 list
print(type(list(tuple_list)))    # <class 'list'>

dictionary 字典的使用

# case
dictionary = {"name": "小明",
              "age": 18, }
  • 取值
print(dictionary["name"])   # 小明
  • 修改/新增
# 如果 key 存在,则修改键值对
dictionary["name"] = "张三"
# 如果 key 不存在,则新增键值对
dictionary['gender'] = "男"

print(dictionary["gender"])   # 男
print(dictionary["name"])   # 张三
  • pop 删除
dictionary.pop("name")
print("打印字典:", dictionary)  # 打印字典: {'age': 18, 'gender': '男'}
  • len 统计键值对的length
print("统计键值对的length:", len(dictionary)) # 统计键值对的length: 2
  • update 合并键值对
new_dictionary = {"classroom": "三年级一班"}
dictionary.update(new_dictionary)
print("合并键值对:", dictionary) 
# 合并键值对: {'age': 18, 'gender': '男', 'classroom': '三年级一班'}
  • 如果合并的键值对中有重复的 key 值。会覆盖原有的键值对
repeat_dictionary = {"age": "2000"}
dictionary.update(repeat_dictionary)
print("重复的键值对:", dictionary)     
# 重复的键值对: {'age': '2000', 'gender': '男', 'classroom': '三年级一班'}
  • clear() 清空 dictionary(字典)
dictionary.clear()
print(dictionary)   # {}
  • 迭代遍历 dictionary
zhangsan_dictionary = {"name": "张三",
                       "age": 18,
                       "phone": 10000000000}

# i 是每次迭代遍历时,获取到的键值对的 key
for i in zhangsan_dictionary:
    # print("%s - %s " % (i,zhangsan_dictionary[i]))
    print("key 是:%s - 值是:%s " % (i, zhangsan_dictionary[i]))

结果

image.png

String 的基础方法

  • isspace() 判断是否为 空白
new_str = " "
print(new_str.isspace())    # True
new_str = " 1"
print(new_str.isspace())    # False
  • 判断是否为数字,都不能判断小数
numb_str = "1"
print(numb_str.isdecimal())     # True    全角数字
numb_str = "\u00b2"
print(numb_str)
print(numb_str.isdigit())     # True 可以识别 unicode 字符串
numb_str = "一千零一"
print(numb_str.isnumeric())     # True  可以识别 中文数字
  • startswith 判读以指定字符串开始
hello_str = "hello world"
# 语法: str.startswith(str, beg=0,end=len(string));
# 如果包含指定字符串返回 True , 否则返回 False
print("查找指定字符串开始:", hello_str.startswith("hello"))      # 查找指定字符串开始: True
  • endswith 判断是否以指定字符串结尾
# 语法:str.endswith(suffix[, start[, end]])
# 如果字符串中含有指定的后缀返回 True , 否则返回 False
print("判断是否以指定字符串:", hello_str.endswith("world"))      # 判断是否以指定字符串: True
  • index 同样可以查找指定字符串的索引值,但是 查找不到,会报错
  • find 查找指定字符串
# 语法: str.find(str, beg=0, end=len(string))
# 查找是否有指定的字符串,有则返回指定字符串开始的索引值,否则返回 -1
print("判断是否包含指定字符串:", hello_str.find("llo"))  # 判断是否包含指定字符串: 2
print("判断是否包含指定字符串:", hello_str.find("llo1"))  # 判断是否包含指定字符串: -1
  • replace 替换字符串,返回新的字符串,不会改变原有的字符串
print("替换并返回新的字符串:", hello_str.replace("world", "世界"))    # 替换并返回新的字符串: hello 世界
print("old String: ", hello_str)        # old String:  hello world
  • center 居中对齐
new_str1 = ["\t\n定风波·莫听穿林打叶声",
            "三月七日,沙湖道中遇雨。雨具先去,同行皆狼狈,余独不觉。已而遂晴,故作此词。 ",
            "莫听穿林打叶声,何妨吟啸且徐行。竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生\t\n",
            "料峭春风吹酒醒,微冷,山头斜照却相迎。回首向来萧瑟处,\n归去,也无风雨也无晴。"]
for item in new_str1:
    # strip 去除字符串两边的空白字符,在使用 center 居中字符串
    print("| %s |" % item.strip().center(10, " "))    # | 定风波·莫听穿林打叶声 |
# | 三月七日,沙湖道中遇雨。雨具先去,同行皆狼狈,余独不觉。已而遂晴,故作此词。 |
# | 莫听穿林打叶声,何妨吟啸且徐行。竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生 |
# | 料峭春风吹酒醒,微冷,山头斜照却相迎。回首向来萧瑟处,
# 归去,也无风雨也无晴。 |
  • 拆分和连接
# split() 以指定分隔符进行分割,返回一个新的 list(列表)
pope1_list = new_str2.split()
print(pope1_list)   # ['定风波·莫听穿林打叶声','三月七日', '沙湖道中遇雨', '雨具先去', '同行皆狼狈', '余独不觉', '已而遂晴', '故作此词',
# '莫听穿林打叶声', '何妨吟啸且徐行', '竹杖芒鞋轻胜马', '谁怕?一蓑烟雨任平生', '料峭春风吹酒醒', '微冷', '山头斜照却相迎回首向来萧瑟处', '归去', '也无风雨也无晴']
  • join() 以指定分隔符进行分割,返回一个新的 String(字符串)
join_str = ",".join(pope1_list)
print(join_str)  # 定风波·莫听穿林打叶声,三月七日,沙湖道中遇雨,雨具先去,同行皆狼狈,余独不觉,已而遂晴,故作此词,
# 莫听穿林打叶声,何妨吟啸且徐行,竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生,料峭春风吹酒醒,微冷,山头斜照却相迎回首向来萧瑟处,归去,也无风雨也无晴
  • 切片
    语法:
    list:[start_index: stop_index: step]
    start_index:起始位置,空时默认为0
    stop_index:终点位置,空时默认为 list 长度,注意起点位置与终点索引的关系
    step:步数,空时默认为 1,不能为 0

slice_str = "0123456789"
# 截取从 1 - 5 位置的字符串
print(slice_str[2:6])   # 2345
# 截取从 2 - 末尾的字符串
print(slice_str[2:])       # 23456789
# 截取从 开始 - 5 位置的 String
print(slice_str[:6])    # 012345
# 截取完整的字符串
print(slice_str[0::])   # 0123456789
# 从开始位置,每隔一个字符截取 String
print(slice_str[0::2])  # 02468
# 从 1 开始,每隔一个取一个
print(slice_str[1::2])  # 13579
# 截取从 2 - 末尾-1 的字符
print(slice_str[2:-1:])     # 2345678
# 截取 String 末尾两个 字符
print("末尾两个字符:", slice_str[-2:])    # 末尾两个字符: 89
# 逆序排列
print("逆序:", slice_str[-1::-1])     # 逆序: 9876543210   start_index 这时为 list 最后一位 -1(可以省略)

Python 内置函数

new_list = ['1', '2', '3', '4', ]
  • del() 删除函数
del(new_list[0])
print("返回删除后的lsit:", new_list)  # 返回删除后的lsit: ['2', '3', '4']
del new_list[2]
print("返回删除后的lsit1:", new_list)  # 返回删除后的lsit1: ['2', '3']
del new_list
# 打印已经删除的数据,会报错 undefined
# print("返回删除后的lsit1:", new_list)  # 报错 name 'new_list' is not defined
  • max() 取最大值
t_str = "afsdgdgkijiojopokpojiojndnvkkad"
t_list = [9, 1, 6, 3, 0]
print("求最大值:", max(t_str))      # 求最大值: v
print("求最大值:", max(t_list))      # 求最大值: 9
  • min() 取最小值
print("求最小值:", min(t_str))      # 求最小值: v
print("求最小值:", min(t_list))      # 求最小值: 0
  • max() min() 以 list 中的 key 值进行大小取值,和 value 没有关系
arr_list = {"a": "1", "b": "9", "f": "e", "c": "13", "d": "90", }
print("求arr_list中的最小值:", min(arr_list))     # 求arr_list中的最小值: a
print("求arr_list中的最大值:", max(arr_list))     # 求arr_list中的最大值: f
print("list 进行大小比较: ", [1, 1, 1] > [2, 2, 2])   # list 进行大小比较:  True
print("tuple(元组)进行比较:", ("1", "1", "1") > ("2", "2", "2"))  # tuple(元组)进行比较: True
# dictionary(字典)无法进行比较       not supported between instances of 'dict' and 'dict'
print("dictionary(字典)进行比较:", {"a": "1", "b": "12", "c": "1", } > {"d": "1", "e": "12", "f": "1", })