Python 元组

Posted on 2018-11-29 21:40  缥缈映苍穹  阅读(167)  评论(0)    收藏  举报
# 元组用()表示, 只读列表
tu = ("DNF","LOL","王者荣耀","QQ飞车","炫舞",{},tuple(),[])
print(tu)
tu[1] = "呵呵"   #'tuple' object does not support item assignment
print(tu)

# 元组也有索引和切片
print(tu[3:5])
print(tu[3:7:2])

# 元组有坑
# 空元组
tu = tuple()  # 固定写法
# 元组中如果只有一个元素
tu = (1) # 不是元组 <class 'int'>
tu = (1, )  # 这个是元组  <class 'tuple'>
print(type(tu))

# 好习惯: 写元组的时候末尾加个逗号

tu = ("锅包肉","酸菜炖粉条+五花肉","红烧鲤鱼","红烧肉")
# # 元组也是可迭代的
for item in tu: # 可以使用for循环
    print(item)

tu = (1,"哈哈","胡辣汤",["忍者","神龟"])
# tu[1] = "呵呵"  #元组不可变
tu[3] = ["我是新列表"] #改变了指向, 报错
tu[3].append("孙悟空") # 元组没改, 改的是元素内部  没有改变元组指向, 不报错
print(tu)