Python 列表練習



Python 列表練習 1

Python 程式用於查詢給定列表中的唯一數字。

L1 = [1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2]
L2 = []
for x in L1:
   if x not in L2:
      L2.append(x)
print (L2)

它將產生以下輸出

[1, 9, 6, 3, 4, 5, 2, 7, 8]

Python 列表練習 2

Python 程式用於查詢列表中所有數字的總和。

L1 = [1, 9, 1, 6, 3, 4]
ttl = 0
for x in L1:
   ttl+=x
print ("Sum of all numbers Using loop:", ttl)
ttl = sum(L1)
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
L1 = []
for i in range(5):
   x = random.randint(0, 100)
   L1.append(x)
print (L1)

它將產生以下輸出

[77, 3, 20, 91, 85]
廣告