当前分类:300例题>>正文

Python示例:计算元组长度

来源:互联网   更新时间:2023年6月23日  

Python 示例

写一个 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://6yhj.com/leku-p-4433.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: css