一、元组
和列表差不多,也是存一组数据。
区别在于元组一旦创建,就不可以更改,所以又称作只读列表。
元组只有两个方法:
①统计:元组名.count('***')
②获取下标:元组名.index('***')
1 #!-*- coding:utf-8 -*- 2 # Author:Steve 3 4 store=('math','english','chinese') 5 print ('\nNumber of books in the store is:',store) 6 7 new_store=('computer','sport','chinese',store) 8 print ('\nNumber of books in the new store os:',new_store) 9 print ('\nAll books in the new store are:',new_store) 10 print ('\nBooks appended from old store are:',new_store[2]) 11 print ('\nFirst book appened from old store is:',new_store[3][2]) 12 13 print('The number of chinese book in oldstore :{}'.format(store.count('english'))) 14 15 print("Where's the sports book?\n{}".format(new_store.index('sport')))
二、字符串、列表、元组 之间的相互转换
①将字符串转换为元组:
1 #!-*- coding:utf-8 -*- 2 # Author:Steve 3 name = "Steve" 4 tuple_of_name = tuple(name) 5 print(tuple_of_name)
②将列表转换为元组:
1 #!-*- coding:utf-8 -*- 2 # Author:Steve 3 age = ["古稀之年",22,33] 4 tuple_of_age= tuple(age) 5 print (tuple_of_age)
③将元组转换为列表:
1 #!-*- coding:utf-8 -*- 2 # Author:Steve 3 salary = ("年入百万", 30000, 0) 4 list_of_salary = list(salary) 5 print(list_of_salary)
④将元组转化为字符串(有两种方法):
Ⅰ.写for循环,一个一个的循环,因为元素中既有数字,又有字母,所以得定义一个空,然后循环的时候转换成str类型,
才能进行相加,一个一个的循环
1 #!-*- coding:utf-8 -*- 2 # Author:Steve 3 sex= ("girl","boy") 4 str_of_sex = "" 5 for n in sex: 6 b = str(n) 7 str_of_sex += b 8 print(str_of_sex)
Ⅱ.元组里面都是字符串的时候,我们就可以用join的方法进行拼接了
注意:有数字就不能用join了,就得用第一种方法写for循环了
1 #!-*- coding:utf-8 -*- 2 # Author:Steve 3 books = ("Chinese", "English") 4 str_of_books = "_".join(books) 5 print(str_of_books)
三、修改元组里面的二级列表中的元素
1 #!-*- coding:utf-8 -*- 2 # Author:Steve 3 tuple = ("11", "22", ["33", ("0", 66, "99",), 90]) 4 tuple[2][0] = "333" 5 print(tuple)
四、适用情况:
所写程序中的数据不能被改动。比如:数据库连接配置文件中的数据
也可以提醒他人不要修改这个元组中的数据。