Python 元组练习
示例1
Python程序查找给定元组中的独特数字−
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)
将会产生以下输出。
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)
示例2
Python 程序,用于找出元组中所有数字的和−
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)
它将产生以下 输出 −
Sum of all numbers Using loop: 24
Sum of all numbers sum() function: 24
示例3
创建一个包含5个随机整数的元组的Python程序 −
import random
t1 = ()
for i in range(5):
x = random.randint(0, 100)
t1+=(x,)
print (t1)
它将产生以下的 输出 −
(64, 21, 68, 6, 12)