寫一個 Python 程序來找到元組的長度。在這個例子中,我們聲明了整數和字元串元組,並使用 Python len 函數來查找這些元組的長度。
# Tuple Length
intTuple = (10, 20, 30, 40, 50)
print("Tuple Items = ", intTuple)
inttupleLength = len(intTuple)
print("Tuple Length = ", inttupleLength)
strTuple = ('apple', 'Mango', 'kiwi')
print("String Tuple Items = ", strTuple)
strtupleLength = len(strTuple)
print("String Tuple Length = ", strtupleLength)
Tuple Items = (10, 20, 30, 40, 50)
Tuple Length = 5
String Tuple Items = ('apple', 'Mango', 'kiwi')
String Tuple Length = 3
尋找元組長度的 Python 程序
在這個例子中,我們聲明了嵌套和混合元組。如果您想要 Python 嵌套元組長度,您必須使用該嵌套項的索引位置。例如,len(mTuple[4])返回嵌套元組(1,2,3,4) 的長度
mTuple = ('Apple', 22, 'Kiwi', 45.6, (1, 2, 3, 4), 16, [10, 30, 70])
print("Mixed Tuple Items = ", mTuple)
mtupleLength = len(mTuple)
print("Mixed Tuple Length = ", mtupleLength)
nestedtupleLength = len(mTuple[4])
print("Nested Tuple Length = ", nestedtupleLength)
nestedlistLength = len(mTuple[6])
print("List Nested inside a Tuple Length = ", nestedlistLength)
在這個 Python 程序中,我們聲明了一個空元組,並將用戶給定的值添加到該元組中,並計算長度。
# Tuple Length
intTuple = ()
number = int(input("Enter the Total Tuple Items = "))
for i in range(1, number + 1):
value = int(input("Enter the %d value = " %i))
intTuple += (value,)
print("Tuple Items = ", intTuple)
inttupleLength = len(intTuple)
print("Tuple Length = ", inttupleLength)
Enter the Total Tuple Items = 4
Enter the 1 value = 22
Enter the 2 value = 99
Enter the 3 value = 128
Enter the 4 value = 65
Tuple Items = (22, 99, 128, 65)
Tuple Length = 4
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129634.html