python的元组的基本使用

1、

元组的定义

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

 

2、

python
info_tuple = ("zhangsan", 18, 1.75)
```

#### 创建空元组

```python
info_tuple = ()
```

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

```python
info_tuple = (50, )

 

在 `ipython3` 中定义一个 **列表**,例如:`name_list = []`
* 输入 `name_list.` 按下 `TAB` 键,`ipython` 会提示 **列表** 能够使用的 **方法** 如下:

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))

 

元祖的遍历

info_tuple = ("zhangsan", 18, 1.75)

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

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

循环遍历

* **取值** 就是从 **元组** 中获取存储在指定位置的数据
* **遍历** 就是 **从头到尾** **依次** 从 **元组** 中获取数据

```python
# for 循环内部使用的变量 in 元组
for item in info:

    循环内部针对元组元素进行操作
    print(item)

```

> * 在 `Python` 中,可以使用 `for` 循环遍历所有非数字型类型的变量:**列表**、**元组**、**字典** 以及 **字符串**
> * 提示:在实际开发中,除非 **能够确认元组中的数据类型**,否则针对元组的循环遍历需求并不是很多

 应用场景

* 尽管可以使用 `for in` 遍历 **元组**
* 但是在开发中,更多的应用场景是:
    * **函数的 参数 和 返回值**,一个函数可以接收 **任意多个参数**,或者 **一次返回多个数据**
        * 有关 **函数的参数 和 返回值**,在后续 **函数高级** 给大家介绍
    * **格式字符串**,格式化字符串后面的 `()` 本质上就是一个元组
    * **让列表不可以被修改**,以保护数据安全

info = ("zhangsan", 18)

print("%s 的年龄是 %d" % info)

 

元组和列表之间的转换

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

```python
list(元组) 
```

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

```python
tuple(列表)
```

 

格式化字符串

info_tuple = ("小明", 21, 1.85)

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

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

print(info_str)

 

 字典的定义

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

```python
xiaoming = {"name": "小明",
            "age": 18,
            "gender": True,
            "height": 1.75}
```

 

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

print(xiaoming)

 

字典的基本使用增加或者修改

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)

字典常用操作

* 在 `ipython3` 中定义一个 **字典**,例如:`xiaoming = {}`
* 输入 `xiaoming.` 按下 `TAB` 键,`ipython` 会提示 **字典** 能够使用的函数如下:

```
In [1]: xiaoming.
xiaoming.clear       xiaoming.items       xiaoming.setdefault
xiaoming.copy        xiaoming.keys        xiaoming.update
xiaoming.fromkeys    xiaoming.pop         xiaoming.values
xiaoming.get         xiaoming.popitem 

 

循环遍历

* **遍历** 就是 **依次** 从 **字典** 中获取所有键值对

```python
# for 循环内部使用的 `key 的变量` in 字典
for k in xiaoming:

    print("%s: %s" % (k, xiaoming[k]))

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

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

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

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

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

print(xiaoming_dict)

 

接下来就是讲怎么样遍历字符串,

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

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

     #下面的%s 是代表键,第二个代表值     接下来后面的逗号是代码参数传过来的值
    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)

 

字符串

### 4.1 字符串的定义

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

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

```python
string = "Hello Python"

for c in string:
    print(c)

```

如果字符串过多的情况下,单引号可以把双引号把他包过了所以出现下面的例子

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

print(str2)
print(str1[6])

for char in str2:

    print(char)

 

 

重点推荐记住下面的几个方法使用

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"))

 

字符串的常用操作

* 在 `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 的新字符串 |

 

# 1. 判断空白字符
space_str = "      \t\n\r"

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())

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值