Python 运算符&公共方法&容器类型转换

运算符&公共方法&容器类型转换

一、运算符

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

1. +

# 字符串
str1 = 'hello'
str2 = ' world'
str3 = str1 + str2
print(str3)  # hello world

# 列表
list1 = [10, 12]
list2 = [13, 14]
list3 = list1 + list2
print(list3) # [10, 12, 13, 14]

# 元组
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2 
print(t3) # (1, 2, 3, 4)

2. *

# 1 字符串
print('-' * 10) # ----------
# 2 列表
list1 = ['hello']
print(list1 * 3) # ['hello', 'hello', 'hello']
# 3 元组
t1 = ('world',)
print(t1 * 3) # ('world', 'world', 'world')

3. in 、 not in

# 1 字符串
print('a' in 'happy')
print('a' not in 'happy')
# 2 列表
list1 = ['hello', 'world']
print('hello' in list1)
print('hello' not in list1)

# 3 元组
t1 = ('world', 'hello')
print('hello' in t1)
print('hello' not in t1)
"""
True
False
True
False
True
False
"""

二、 常用方法

函数 描述
len(容器) 计算容器中元素个数
del 或 del() 删除
max() 返回容器中元素最大值
min() 返回容器中元素最小值
range(start,end,setp) 生成从start到end的数字,步长为step,供for循环使用
enumerate() 函数⽤于将⼀个可遍历的数据对象(如列表、元组或字符串)组合为⼀个索引序列,同时列出数据和数据下标,⼀般⽤在 for 循环当中。

len

# 1. 字符串
str1 = 'abcdefg'
print(len(str1)) # 7
# 2. 列表
list1 = [10, 20, 30, 40]
print(len(list1)) # 4
# 3. 元组
t1 = (10, 20, 30, 40, 50)
print(len(t1)) # 5
# 4. 集合
s1 = {10, 20, 30}
print(len(s1)) # 3
# 5. 字典
dict1 = {'name': 'Rose', 'age': 18}
print(len(dict1)) # 2

del

list1 = [1, 3, 5]
del(list1[1])
print(list1) # [1, 5]
del list1[1]
print(list1) # [1]

max(序列)

min 与max相反

list2 = [1, 8, 3, 5]
print(max(list2)) # 8

list3 = 'cbah'
print(max(list3)) # h

range([起始默认0],结束不包含,[步长默认1])

for i in range(10):
    print(i, end=" ")
# 0 1 2 3 4 5 6 7 8 9

for i in range(1, 10, 1):
    print(i, end=" ")
# 1 2 3 4 5 6 7 8 9
for i in range(1, 10, 2):
    print(i, end=" ")
# 1 3 5 7 9 

range 生成的序列不包含end数字

enumerate(可遍历对象, start=0)

list1 = 'abcdef'
for i in enumerate(list1):
    print(i)
"""
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
"""
for idx, char in enumerate(list1, start=1):
    print(f"下标是{idx}, 值为:{char}")
"""
下标是1, 值为:b
下标是2, 值为:c
下标是3, 值为:d
下标是4, 值为:e
下标是5, 值为:f
"""

三、容器类型转换(list tuple set)

1. 转换list(元组集合)

t1 = ('a', 'b', 'c')
print(list(t1)) # ['a', 'b', 'c']
s1 = {122, 150, 166}
print(list(s1)) # [122, 150, 166]

2. 转换set(列表元组)

list1 = ['hello', 'wolrd', 'python']
t1 = ('hello', 'wolrd', 'python')
print(set(list1))
print(set(t1))
# {'wolrd', 'python', 'hello'}

3. 转换tuple(列表集合)

list1 = [10, 20, 30, 40, 50, 20]
s1 = {100, 200, 300, 400, 500}
print(tuple(list1)) # (10, 20, 30, 40, 50, 20)
print(tuple(s1)) # (400, 100, 500, 200, 300)

你可能感兴趣的:(Python,python,开发语言)