与 list 不同,tuple 一旦定义(初始化),元素便不能再修改,且其使用()
来定义。
# 普通元组
info = ("wayne17", "male", 34)
# 嵌套元组
my_info = ("vivian", ("girl", 13), "student", 1999)
与 list 相同,直接通过下标访问,info[-1]
表示元组最后一个元素。
info.index("male") # 返回元素 "male" 第一次出现的索引 1
my_info.index(("girl", 13)) # 返回 1
info.count(34) # 返回 34 出现的次数1
info_list = list(info)
# info_list = ['wayne17', 'male', 34]
name_list = ["vivian", "wayne", "lara"]
name_tuple = tuple(name_list)
print_str = "my name is %s, I am %d now."
info = ("wayne", 17)
print (print_str % info)
# my name is wayne, I am 17 now.
def sum(a, b):
return a+b
num = (2.3, 45)
print sum(num) # 47.3