编写一个 Python 程序来查找元组中最大和最小的项。这里,我们使用元组最大和最小函数来返回最大和最小的元组项。
# Tuple Largest and Smallest Item
lgsmTuple = (78, 67, 44, 9, 34, 88, 11, 122, 23, 19)
print("Tuple Items = ", lgsmTuple)
print("Largest Item in lgsmTuple Tuple = ", max(lgsmTuple))
print("Smallest Item in lgsmTuple Tuple = ", min(lgsmTuple))
寻找元组中最大和最小项的 Python 程序
在这里,我们使用元组排序函数以升序对元组进行排序。接下来,我们打印第一个(最小的)和最后一个(最大的)索引位置项目。
# Tuple Largets and Smallest Item
lgsmTuple = (15, 76, 34, 79, 89, 33, 14, 10, 65, 55)
print("Tuple Items = ", lgsmTuple)
lgsmTuple = sorted(lgsmTuple)
print("Largest Item in lgsmTuple Tuple = ", lgsmTuple[len(lgsmTuple) - 1])
print("Smallest Item in lgsmTuple Tuple = ", lgsmTuple[0])
Tuple Items = (15, 76, 34, 79, 89, 33, 14, 10, 65, 55)
Largest Item in lgsmTuple Tuple = 89
Smallest Item in lgsmTuple Tuple = 10
在这个 Python 示例中,我们将 Tuple 第一个值分配给最大和最小的变量。第一个 if 条件(if(tup maximum< lgsmTuple[I])) examines whether the current Tuple item is less than the tupLargest. If True, assign that Tuple value to the largest item and also save the index value. Similarly, the second if statement (if(tupSmallest >lgsmTuple[I])检查元组项是否大于 tup minist。如果为真,则将该元组值赋给最小值,并保存索引位置。
# Tuple Largets and Smallest Item
lgsmTuple = (25, 17, 33, 89, 77, 10, 64, 11, 55)
print("Tuple Items = ", lgsmTuple)
tupLargest = lgsmTuple[0]
tupSmallest = lgsmTuple[0]
for i in range(len(lgsmTuple)):
if(tupLargest < lgsmTuple[i]):
tupLargest = lgsmTuple[i]
tupLargestPos = i
if(tupSmallest > lgsmTuple[i]):
tupSmallest = lgsmTuple[i]
tupSmallestPos = i
print("Largest Item in lgsmTuple Tuple = ", tupLargest)
print("Largest Tuple Item index Position = ", tupLargestPos)
print("Smallest Item in lgsmTuple Tuple = ", tupSmallest)
print("Smallest Tuple Item index Position = ", tupSmallestPos)
Tuple Items = (25, 17, 33, 89, 77, 10, 64, 11, 55)
Largest Item in lgsmTuple Tuple = 89
Largest Tuple Item index Position = 3
Smallest Item in lgsmTuple Tuple = 10
Smallest Tuple Item index Position = 5
在这个 Python 程序中,我们创建了两个不同的函数,分别返回最大和最小的元组。
# Tuple Max Item
def tupleLargest(lgsmTuple):
tupLargest = lgsmTuple[0]
for i in lgsmTuple:
if(tupLargest < i):
tupLargest = i
return tupLargest
def tupleSmallest(lgsmTuple):
tupSmallest = lgsmTuple[0]
for i in lgsmTuple:
if(tupSmallest > i):
tupSmallest = i
return tupSmallest
lgsmTuple = (33, 56, 22, 18, 2, 76, 45, 95, 77, 15)
print("Tuple Items = ", lgsmTuple)
lar = tupleLargest(lgsmTuple)
print("Largest Item in lgsmTuple Tuple = ", lar)
smt = tupleSmallest(lgsmTuple)
print("Smallest Item in lgsmTuple Tuple = ", smt)
Tuple Items = (33, 56, 22, 18, 2, 76, 45, 95, 77, 15)
Largest Item in lgsmTuple Tuple = 95
Smallest Item in lgsmTuple Tuple = 2