【无为则无心&Python基础】— 34、Python序列的通用方法

本文介绍了Python序列的通用运算符和方法,包括加号、乘号、或运算,以及方法如`enumerate`、`range`等。详细讲解了`range`函数的语法和使用示例,并提到了`zip`函数在遍历数据时的作用。此外,还探讨了将序列转换为元组、列表和集合的函数,强调了集合在去重中的应用。
摘要由CSDN通过智能技术生成

序列的公共方法

公共操作指的就是所学过的数据序列基本上都支持的操作。

以下是总结内容:

一、运算符

运算符 描述 支持的容器类型
+ 合并 字符串、列表、元组
* 复制 字符串、列表、元组
in 元素是否存在 字符串、列表、元组、字典
not in 元素是否不存在 字符串、列表、元组、字典

@1.+加号

+可以将两个序列拼接为一个序列。

# 1. 字符串 `+`号
str1 = 'aa'
str2 = 'bb'
str3 = str1 + str2
print(str3)  # aabb

# 2. 列表 `+`号
list1 = [1, 2]
list2 = [10, 20]
list3 = list1 + list2
print(list3)  # [1, 2, 10, 20]

# 3. 元组 `+`号
t1 = (100, 200)
t2 = (10, 20)
t3 = t1 + t2
print(t3)  # (100, 200, 10, 20)

# 4.字典 `+`号
# 结果:TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
dict1 = {
   'name': 'Python'}
dict2 = {
   'age': 30}
dict3 = dict1 + dict2
print(dict3)  # 异常

@2.*乘号

可以将序列重复指定的次数。

# 1. 字符串
# 结果:----------
print('-' * 10) 

# 2. 列表
# 结果:['hello', 'hello', 'hello', 'hello']
list1 = ['hello']
print(list1 * 4)  

# 3. 元组
# 结果:('world', 'world', 'world', 'world')
t1 = ('world',)
print(t1 * 4) 

# 字典
# 结果:TypeError: unsupported operand type(s) for *: 'dict' and 'int'
dict1 = {
   'name': 'Python'}
print(dict1 * 4)  # 异常

@3.innot in

# 1. 字符串
print('a' in 'abcd')  # True
print('a' in 'hijk')  # False
print('a' not in 'abcd')  # False
print('a' not in 'hijk')  # True

# 2. 列表
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值