您的位置:

Python 程序:寻找元组中最小项

编写一个 Python 程序来查找元组中最小或最小的项。这里,我们使用 Tuple min 函数(min(smTuple)))返回最小 Tuple 项。

# Tuple Min Item

smTuple = (9, 11, 22, 45, 33, 5, 17, 30)
print("Tuple Items = ", smTuple)

print("Smallest Item in smTuple Tuple = ", min(smTuple))

寻找元组中最小项的 Python 程序

我们使用元组排序函数(sorted(smTuple))以升序对元组进行排序,并打印第一项,即最小项。

# Tuple Min Item

smTuple = (14, 19, 11, 25, 7, 22, 30) 
print("Tuple Items = ", smTuple)

smTuple = sorted(smTuple)
print("Smallest Item in smTuple Tuple = ", smTuple[0])
Tuple Items =  (14, 19, 11, 25, 7, 22, 30)
Smallest Item in smTuple Tuple =  7

在这个 Python 示例中,我们将 Tuple 的第一个值指定为 minimal(tuplesmall = smTuple[0]),for 循环范围从 1 开始,遍历到 smTuple 长度。if 条件(if(图最小> smTuple[I])检查当前 Tuple 项是否小于最小。如果为真,则将该元组值分配给最小值,并将索引值分配给最大值变量。

# Tuple Min Item

smTuple = (25, 33, 55, 17, 2, 40, 30, 65, 29) 
print("Tuple Items = ", smTuple)

tupSmallest = smTuple[0]
for i in range(len(smTuple)):
    if(tupSmallest > smTuple[i]):
        tupSmallest = smTuple[i]
        tupSmallestPos = i

print("Smallest Item in smTuple Tuple     = ", tupSmallest)
print("Smallest Tuple Item index Position = ", tupSmallestPos)
Tuple Items =  (25, 33, 55, 17, 2, 40, 30, 65, 29)
Smallest Item in smTuple Tuple     =  2
Smallest Tuple Item index Position =  4

Python 程序使用函数返回最小元组数。

# Tuple Max Item

def tupleSmallest(smTuple):
    tupSmallest = smTuple[0]
    for i in smTuple:
        if(tupSmallest > i):
            tupSmallest = i
    return tupSmallest

smTuple = (19, 77, 13, 87, 33, 6, 17, 45, 66) 
print("Tuple Items = ", smTuple)

smt = tupleSmallest(smTuple)
print("Smallest Item in smTuple Tuple = ", smt)
Tuple Items =  (19, 77, 13, 87, 33, 6, 17, 45, 66)
Smallest Item in smTuple Tuple =  6