列表、元组、字符串统称叫序列,列表与元组中的各元素的数据类型可以不同,但不能往元组中增删元素,也不能修改元组中元素的值,可以往列表中增删元素,也可以修改列表中元素的值。
thistuple = ("apple", 123,"banana", "cherry") #各元素的数据类型不相同
thistuple[4] = "orange" #会引发错误
print(thistuple)
判断是否为一个元组,不是看圆括号是否存在,而是判断元素后是否跟逗号,注意包含多个元素的元组最后一个元素可以不用跟逗号。如下代码所示。
tuple1 = (1) #int类型
tuple1 = 10,20,30,40 #元组类型
print(type(tuple1))
tuple1 = 10, #元组类型
print(type(tuple1))
print((8)*8) #值为64的数
print((8,)*8) #内容为8个8的元组
多个元组可以通过加号(+)进行前后连接,下面代码第二行是三个元组的前后拼接,重新开辟了一块内存空间,并且temp重新指向了新的内存空间,原来的内存空间已经没有变量指向它了,会被垃圾回收机制收回,这个原理与JAVA相同。
temp = ('张三','李四','王五','麻六')
temp = temp[:2]+("张三丰",)+temp[2:] #三个元组的拼接
print(temp)
在以下代码中,tuple1中元素的数据类型不相同,count函数用来统计元组中值为"bb"的元素个数,输出结果为3。index函数用来求值为"bb"的首个元素的下标,输出结果为2。
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return self.name+":"+str(self.age)
tuple1 = ('aa',123,'bb',Student("zs",18),'bb','bb')
print(tuple1.count("bb")) #输出结果为3
print(tuple1.index("bb")) #输出结果为2
有时候,实参个数不确定,这时可以在形参中用一个元组来接收个数不确定的众多实参的值。如以下代码所示,*toings这个形参其实是定义了一个元组,它接收并保存了'mushrooms','green peppers', 'extra cheese'这三个实参值。
def make_pizza(*toings):
for topping in toings:
print("-"+topping)
make_pizza('mushrooms','green peppers','extra cheese')
与以上类似,当实参以键值对的形式出现,并且键值对的个数不确定时,可以在形参定义一个字典,用来接收并保存实参中个数不确定的键值对,如下代码中,'lihui'这个值传给了first这个形参,'li'这个值传给了last这个值,location='changsha',age=18这两个键值对传给了**user_info这个字典。
def make_profile(first,last,**user_info):
profile={}
profile['firsname'] = first
profile['lastname'] = last
for key,value in user_info.items():
profile[key] = value
return profile
userinfo = make_profile('lihui','li',location='changsha',age=18)
print(userinfo)