序列的加法 --- 字符串,列表,元组 可以进行序列的加法
序列具有相加的功能,这个相加同我们数字之间的相加类似,但序列仅支持将两个类型相同的序列加在一起,使用‘+’符号进行操作,若类型不同,则报错
1)相同类型的序列相加,代码如下:
my_list = [1,2,3,4,5,6,7,8,9,] my_list2 = [11,22,33,44,55,66] my_str = 'abcdefghijklmn' my_str2 = 'opqrstuvwxyz' my_tuple = (1,2,3,4,5) my_tuple2 = (6,7,8,9) print('两个列表相加后为:',my_list+my_list2) print('两个字符串相加后为:',my_str+my_str2) print('两个元组相加后:',my_tuple+my_tuple2)
运行结果
两个列表相加后为: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66]
两个字符串相加后为: abcdefghijklmnopqrstuvwxyz
两个元组相加后: (1, 2, 3, 4, 5, 6, 7, 8, 9)2)不同类型的序列相加,代码如下:
my_list = [1,2,3,4,5,6,7,8,9,] my_str = 'abcdefghijklmn' my_tuple = (1,2,3,4,5) print('列表和字符串相加:',my_list+my_str) print('字符串和元组相加:',my_str+my_tuple)
运行结果:
错误提示为:只能将列表(不是“str”)连接到列表,因此在‘+’操作的时候要使用相同类型进行相加
乘法 --- 字符串,列表,元组 可以进行序列的乘法
Python提供序列的相乘功能,这个相乘和算法的不太相同,当一个序列乘上x的时候,生成的新的序列是将原有序列重复的相加了x次。
my_list = [1,2,3,4,5] my_str = 'www.dotcpp.com' my_tuple = (1,2,3,4,5) print('将my_list列表乘上3得到一个新列表为:',my_list*3) print('将my_str字符串乘上3得到一个新字符串为:',my_str*3) print('将my_tuple元组乘上3得到一个新元组为:',my_tuple*3)
运行结果:
成员运算符
“in”,“not in”运算符 支持字符串、列表、元组、集合、字典用于判断某个元素是否属于某个变量
str = 'python' lists = [1,2,3,4,5] tuples = (6,7,8,9,10) sets = {1,2,3,4,5} dicts ={'a':1,'b':3,'c':5} print('字符串:','p' in str,'p' not in str) print('列表:',5 in lists,1 not in lists) print('元组:',11 in tuples,11 not in tuples) print('集合:',1 in sets,6 not in sets) print('字典:','a' in dicts,1 in dicts ,'e' not in dicts)#字典是以键来判断
运行结果: