Python 简明教程
Python Tuple Exercises
Python Tuple Exercise 1
Python 程序,用于查找给定元组中的唯一数字−
Python program to find unique numbers in a given tuple −
T1 = (1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2)
T2 = ()
for x in T1:
if x not in T2:
T2+=(x,)
print ("original tuple:", T1)
print ("Unique numbers:", T2)
它将生成以下 output −
It will produce the following output −
original tuple: (1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2)
Unique numbers: (1, 9, 6, 3, 4, 5, 2, 7, 8)
Python Tuple Exercise 2
Python 程序,用于查找元组中所有数字的总和−
Python program to find sum of all numbers in a tuple −
T1 = (1, 9, 1, 6, 3, 4)
ttl = 0
for x in T1:
ttl+=x
print ("Sum of all numbers Using loop:", ttl)
ttl = sum(T1)
print ("Sum of all numbers sum() function:", ttl)
它将生成以下 output −
It will produce the following output −
Sum of all numbers Using loop: 24
Sum of all numbers sum() function: 24