Python基礎_元組

LibraSolo發表於2020-12-15
# @Time:2020/12/15 21:09
# @Author:李 祥
# @File:Tuple.py
# @Software:PyCharm

# Tuple(元組) 內容不可變,但是包含可變物件
# 相像列表list
#
tup1 = ()  # 建立空元組
print(tup1, type(tup1))

tup1 = (50)
tup2 = (50,)  # 元組的必備條件為 , 單元素最後,不可省。 多元素可省略
print(tup1, type(tup1))
print(tup2, type(tup2))

tup1 = 50, 60, 70
tup2 = 50,
print(tup1, type(tup1))
print(tup2, type(tup2))  # 建立元組可以不加() 不推薦


# 連線(增)
tup1 = (1, 2, 3)
tup2 = (4, 5, 6)
tup = tup1 + tup2
print(tup, type(tup))

# 刪(刪除元組物件,不可刪內部元素)
tup1 = (1, 2, 3)
print(tup1)
del tup1
print(tup1) # 報錯,因為已經刪除

# 改 (只能更改內部可變變數)
list1 = [2, 3]
tup1 = (1, list1)
print(tup1)
list1.append(4)
print(tup1)

# 查
tup1 = (1, 2, 3)
print(tup1[0])  # 根據下標訪問
print(tup1[::-1])   # 切片

# 迴圈
tup1 = (1, 2, 3)
for i in tup1:
    print(i)

# in    not in
tup1 = (1, 2, 3)
if 3 in tup1:
    print("true")
else:
    print("false")

# 計數 count 最大最小max min 求和 sum 長度 len
# 類比list

# 強制型別轉換 tuple()

# 字串
s = "student"
tup = tuple(s)
print(tup, type(tup))

# 列表
list1 = [1, 2, 3]
tup = tuple(list1)
print(tup, type(tup))

# 生成器物件 (後期詳細補充)
s = (i*2 for i in range(5))
print(tuple(s))

相關文章