美文网首页
Python学习

Python学习

作者: 逛逛_堆栈 | 来源:发表于2021-04-03 14:52 被阅读0次

第八天

今天简单总结一下Python中公共的运算符以及方法。

1、公共操作-运算符

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

公共操作+号

str1 = 'str1'
str2 = 'str2'
list1 = [1,2,3]
list2 = [4,5,6]
tuple1 = (1,3,5)
tuple2 = (2,4,5)
dict1 = {'name':'zhangsan'}
dict2 = {'age':20}
# +号是合并
print(str1 + str2)  # str1str2
# 列表合并
print(list1 + list2)  #[1, 2, 3, 4, 5, 6]
# 元组合并
print(tuple1 + tuple2)  # (1, 3, 5, 2, 4, 5)
# 字典合并
print(dict1 + dict2)
#unsupported operand type(s) for +: 'dict' and 'dict'

公共操作*号

str1 = 'str1'
list1 = [1,2]
tuple1 = (1,3)
dict1 = {'name':'zhangsan'}
print(str1*5)  #str1str1str1str1str1
print(list1*5) #[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
print(tuple1*5) #(1, 3, 1, 3, 1, 3, 1, 3, 1, 3)
print(dict1*5) #unsupported operand type(s) for *: 'dict' and 'int'

公共操作in和not in

str1 = 'str1'
list1 = [1,2]
tuple1 = (1,3)
dict1 = {'name':'zhangsan','age':19}
print('a' in str1)  #False
print('s' not in str1) #False
print(2 in list1) #True
print(3 not in list1) #True
print(2 in tuple1) # False
print(3 not in tuple1) #False
print('name' in dict1) #True
print('name' not in dict1) #False
print('name' in dict1.keys()) #True
print('name' in dict1.values()) #False

2、公共操作-方法

函数 描述
len() 计算容器中元素的个数
del() 删除
max() 返回容器中元素最大值
min() 返回容器中元素最小值
range(start,end,step) 生成从start到end的数字,步长step,让for循环使用
enumerate() 将一个可遍历的数据对象组合成一个索引序列,一般用于for循环

公共操作len()方法

str1 = 'hello python'
list1 = [1,2]
tuple1 = (1,3)
dict1 = {'name':'zhangsan','age':19}
print(len(str1)) # 12
print(len(list1)) # 2
print(len(tuple1)) # 2
print(len(dict1)) # 2

公共操作del()方法

str1 = 'hello python'
list1 = [1,2]
del str1
# del(str1)
print(str1) # name 'str1' is not defined
del list1[0]
print(list(list1)) # [2]

公共操作max()和min()方法

str1 = 'hello python'
list1 = [1,2,99,44,55]
print(max(str1))  # y
print(max(list1))  #99
print(min(list1)) # 1
print(min(str1))  # 空格

公共操作range函数

range()函数的语法:range(start,end,step) 类似于python中的切片 end是取不到的,step步长默认值为1。

range1 = range(1,10,1)
print(list(range1))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 循环遍历
for i in range(1,10,2):
    print(i,end=' ')  # 1 3 5 7 9

公共操作enumerate函数

enumerate()函数语法:enumerate(可遍历对象,start = 0)

list = ['a','b','c','d','e']
for i in enumerate(list):
    print(i,end = ' ')
# (0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e')
for i in enumerate(list,1):
    print(i,end = ' ')
# (1, 'a') (2, 'b') (3, 'c') (4, 'd') (5, 'e')

3、容器类型转换

tuple()函数

tuple()函数,将序列转换为元组

list = ['a','b','c','d','e','a','c']
tuple1 = tuple(list)
print(tuple1)
#('a', 'b', 'c', 'd', 'e', 'a', 'c')

list()函数

list()函数,将序列转换为列表

set1 = {'a','b','c','d','e'}
list1 = list(set1)
print(list1)
# ['e', 'b', 'a', 'd', 'c']

set()函数

set函数,将序列转换为集合

list1 = ['a','b','c',3,'b',5,'c',3]
set1 = set(list1)
print(set1)
# {'b', 3, 5, 'a', 'c'}

相关文章

网友评论

      本文标题:Python学习

      本文链接:https://www.haomeiwen.com/subject/cdchkltx.html