Python 元組練習



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)

Python 元組練習 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

Python 元組練習 3

Python 程式用於建立一個包含 5 個隨機整數的元組 -

import random
t1 = ()
for i in range(5):
   x = random.randint(0, 100)
   t1+=(x,)
print (t1)

它將產生以下輸出 -

(64, 21, 68, 6, 12)
廣告