Python 基础2

列表

1.列表的定义

- List(列表) 是 Python 中使用 最频繁 的数据类型,在其他语言中通常叫做 数组
- 专门用于存储 一串 信息
- 列表用 [] 定义,数据 之间使用 , 分隔
- 列表的 索引 从 0 开始

2.列表的操作

列表.insert(索引, 数据) | 在指定位置插入数据
列表.append(数据) | 在末尾追加数据
列表.extend(列表2) | 将列表2 的数据追加到列表
列表[索引] = 数据 | 修改指定索引的数据
del 列表[索引] | 删除指定索引的数据
列表.remove[数据] | 删除第一个出现的指定数据
列表.pop | 删除末尾数据
列表.pop(索引) | 删除指定索引数据
列表.clear | 清空列表
len(列表) | 列表长度
列表.count(数据) | 数据在列表中出现的次数
列表.sort() | 升序排序
列表.sort(reverse=True) | 降序排序
列表.reverse() | 逆序、反转

name_list = ["zhangsan", "lisi", "wangwu"]

# 1. 取值和取索引
# list index out of range - 列表索引超出范围
print(name_list[2])

# 知道数据的内容,想确定数据在列表中的位置
# 使用index方法需要注意,如果传递的数据不在列表中,程序会报错!
print(name_list.index("wangwu"))

# 2. 修改
name_list[1] = "李四"
# list assignment index out of range
# 列表指定的索引超出范围,程序会报错!
# name_list[3] = "王小二"

# 3. 增加
# append 方法可以向列表的末尾追加数据
name_list.append("王小二")
# insert 方法可以在列表的指定索引位置插入数据
name_list.insert(1, "小美眉")

# extend 方法可以把其他列表中的完整内容,追加到当前列表的末尾
temp_list = ["孙悟空", "猪二哥", "沙师弟"]
name_list.extend(temp_list)

# 4. 删除
# remove 方法可以从列表中删除指定的数据
name_list.remove("wangwu")
# pop 方法默认可以把列表中最后一个元素删除
name_list.pop()
# pop 方法可以指定要删除元素的索引
name_list.pop(3)
# clear 方法可以清空列表
name_list.clear()

print(name_list)

del 关键字

name_list = ["张三", "李四", "王五"]

# (知道)使用 del 关键字(delete)删除列表元素
# 提示:在日常开发中,要从列表删除数据,建议使用列表提供的方法
del name_list[1]

# del 关键字本质上是用来将一个变量从内存中删除的
name = "小明"

del name

# 注意:如果使用 del 关键字将变量从内存中删除
# 后续的代码就不能再使用这个变量了
print(name)

print(name_list)

统计

name_list = ["张三", "李四", "王五", "王小二", "张三"]

# len(length 长度) 函数可以统计列表中元素的总数
list_len = len(name_list)
print("列表中包含 %d 个元素" % list_len)

# count 方法可以统计列表中某一个数据出现的次数
count = name_list.count("张三")
print("张三出现了 %d 次" % count)

# 从列表中删除第一次出现的数据,如果数据不存在,程序会报错
name_list.remove("张三")

print(name_list)

排序

name_list = ["zhangsan", "lisi", "wangwu", "wangxiaoer"]
num_list = [6, 8, 4, 1, 10]

# 升序
# name_list.sort()
# num_list.sort()

# 降序
# name_list.sort(reverse=True)
# num_list.sort(reverse=True)

# 逆序(反转)
name_list.reverse()
num_list.reverse()

print(name_list)
print(num_list)

3.循环遍历

name_list = ["张三", "李四", "王五", "王小二"]

# 使用迭代遍历列表
"""
顺序的从列表中依次获取数据,每一次循环过程中,数据都会保存在 
my_name 这个变量中,在循环体内部可以访问到当前这一次获取到的数据

for my_name in 列表变量:

    print("我的名字叫 %s" % my_name)

"""
for my_name in name_list:

    print("我的名字叫 %s" % my_name)

元组

1.元组的定义

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

2 元组常用操作

info_tuple = ("zhangsan", 18, 1.75, "zhangsan")
# 1. 取值和取索引
print(info_tuple[0])
# 已经知道数据的内容,希望知道该数据在元组中的索引
print(info_tuple.index("zhangsan"))

# 2. 统计计数
print(info_tuple.count("zhangsan"))
# 统计元组中包含元素的个数
print(len(info_tuple))

3 遍历,格式化

info_tuple = ("zhangsan", 18, 1.75)

# 使用迭代遍历元组
for my_info in info_tuple:

    # 使用格式字符串拼接 my_info 这个变量不方便!
    # 因为元组中通常保存的数据类型是不同的!
    print(my_info)
info_tuple = ("小明", 21, 1.85)

# 格式化字符串后面的 `()` 本质上就是元组
print("%s 年龄是 %d 身高是 %.2f" % info_tuple)

info_str = "%s 年龄是 %d 身高是 %.2f" % info_tuple

print(info_str)

4 元组与列表之间转换

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

  • 使用 tuple 函数可以把列表转换成元组

name_list = ["张三", "李四", "王五", "王小二"]
info_tuple = ("小明", 21, 1.85)

print(type(name_list))
print(type(info_tuple))

name_list = tuple(name_list)
info_tuple = list(info_tuple)

print(type(name_list))
print(type(info_tuple))

字典

 1.字典定义

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

# 字典是一个无序的数据集合,使用print函数输出字典时,通常
# 输出的顺序和定义的顺序是不一致的!
xiaoming = {"name": "小明",
            "age": 18,
            "gender": True,
            "height": 1.75,
            "weight": 75.5}

print(xiaoming)

2.字典的常用操作

xiaoming_dict = {"name": "小明"}

# 1. 取值
print(xiaoming_dict["name"])
# 在取值的时候,如果指定的key不存在,程序会报错!
# print(xiaoming_dict["name123"])

# 2. 增加/修改
# 如果key不存在,会新增键值对
xiaoming_dict["age"] = 18
# 如果key存在,会修改已经存在的键值对
xiaoming_dict["name"] = "小小明"

# 3. 删除
xiaoming_dict.pop("name")
# 在删除指定键值对的时候,如果指定的key不存在,程序会报错!
# xiaoming_dict.pop("name123")

print(xiaoming_dict)
xiaoming_dict = {"name": "小明",
                 "age": 18}

# 1. 统计键值对数量
print(len(xiaoming_dict))

# 2. 合并字典
temp_dict = {"height": 1.75,
             "age": 20}

# 注意:如果被合并的字典中包含已经存在的键值对,会覆盖原有的键值对
xiaoming_dict.update(temp_dict)
print(xiaoming_dict)

# 3. 清空字典
xiaoming_dict.clear()

print(xiaoming_dict)

3.循环遍历

xiaoming_dict = {"name": "小明",
                 "qq": "123456",
                 "phone": "10086"}

# 迭代遍历字典
# 变量k是每一次循环中,获取到的键值对的key
for k in xiaoming_dict:

    print("%s - %s" % (k, xiaoming_dict[k]))
# 使用 多个键值对,存储 描述一个 物体 的相关信息 —— 描述更复杂的数据信息
# 将 多个字典 放在 一个列表 中,再进行遍历
card_list = [
    {"name": "张三",
     "qq": "12345",
     "phone": "110"},
    {"name": "李四",
     "qq": "54321",
     "phone": "10086"}
]

for card_info in card_list:

    print(card_info)

字符串

 1.定义

str1 = "hello python"
str2 = '我的外号是"大西瓜"'

print(str2)
print(str1[6])

for char in str2:
    print(char)

2.常用操作

 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

2.1 判断类型

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.2 查找和替换

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 次

2.3 大小写转换

string.capitalize() 把字符串的第一个字符大写
string.title() 把字符串的每个单词首字母大写
string.lower() 转换 string 中所有大写字符为小写
string.upper() 转换 string 中的小写字母为大写
string.swapcase() 翻转 string 中的大小写

2.4 文本对齐

string.ljust(width) 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
string.rjust(width) 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
string.center(width) 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

2.5 去除空白字符

string.lstrip() 截掉 string 左边(开始)的空白字符
string.rstrip() 截掉 string 右边(末尾)的空白字符
string.strip() 截掉 string 左右两边的空白字符

2.6 拆分和连接

string.partition(str) 把字符串 string 分成一个 3 元素的元组 (str前面, str, str后面)
string.rpartition(str) 类似于 partition() 方法,不过是从右边开始查找
string.split(str="", num) 以 str 为分隔符拆分 string,如果 num 有指定值,则仅分隔 num + 1 个子字符串,str 默认包含 ' ', ' ', ' ' 和空格
string.splitlines() 按照行(' ', ' ', ' ')分隔,返回一个包含各行作为元素的列表
string.join(seq) 以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
hello_str = "hello hello"

# 1. 统计字符串长度
print(len(hello_str))

# 2. 统计某一个小(子)字符串出现的次数
print(hello_str.count("llo"))
print(hello_str.count("abc"))

# 3. 某一个子字符串出现的位置
print(hello_str.index("llo"))
# 注意:如果使用index方法传递的子字符串不存在,程序会报错!
print(hello_str.index("abc"))
# 1. 判断空白字符
space_str = "      	

"

print(space_str.isspace())

# 2. 判断字符串中是否只包含数字
# 1> 都不能判断小数
# num_str = "1.1"
# 2> unicode 字符串
# num_str = "u00b2"
# 3> 中文数字
num_str = "一千零一"

print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())
hello_str = "hello world"

# 1. 判断是否以指定字符串开始
print(hello_str.startswith("Hello"))

# 2. 判断是否以指定字符串结束
print(hello_str.endswith("world"))

# 3. 查找指定字符串
# index同样可以查找指定的字符串在大字符串中的索引
print(hello_str.find("llo"))
# index如果指定的字符串不存在,会报错
# find如果指定的字符串不存在,会返回-1
print(hello_str.find("abc"))

# 4. 替换字符串
# replace方法执行完成之后,会返回一个新的字符串
# 注意:不会修改原有字符串的内容
print(hello_str.replace("world", "python"))

print(hello_str)
# 假设:以下内容是从网络上抓取的
# 要求:顺序并且居中对齐输出以下内容
poem = ["	
登鹳雀楼",
         "王之涣",
         "白日依山尽	
",
         "黄河入海流",
         "欲穷千里目",
         "更上一层楼"]

for poem_str in poem:

    # 先使用strip方法去除字符串中的空白字符
    # 再使用center方法居中显示文本
    print("|%s|" % poem_str.strip().center(10, " "))
# 假设:以下内容是从网络上抓取的
# 要求:
# 1. 将字符串中的空白字符全部去掉
# 2. 再使用 " " 作为分隔符,拼接成一个整齐的字符串
poem_str = "登鹳雀楼	 王之涣 	 白日依山尽 	 
 黄河入海流 		 欲穷千里目 		
更上一层楼"

print(poem_str)

# 1. 拆分字符串
poem_list = poem_str.split()
print(poem_list)

# 2. 合并字符串
result = " ".join(poem_list)
print(result)

3.切片

  切片 方法适用于 字符串、列表、元组

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

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

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

  演练需求
- 1. 截取从 2 ~ 5 位置 的字符串
- 1. 截取从 2 ~ 末尾 的字符串
- 1. 截取从 开始 ~ 5 位置 的字符串
- 1. 截取完整的字符串
- 1. 从开始位置,每隔一个字符截取字符串
- 1. 从索引 1 开始,每隔一个取一个
- 1. 截取从 2 ~ 末尾 - 1 的字符串
- 1. 截取字符串末尾两个字符
- 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])

# 10
print(num_str[::-2])
You are never too old to set another goal or to dream a new dream!!!
原文地址:https://www.cnblogs.com/youguess/p/14308334.html