Python 数组练习
示例1
Python程序查找数组中最大的数字 –
import array as arr
a = arr.array('i', [10,5,15,4,6,20,9])
print (a)
largest = a[0]
for i in range(1, len(a)):
if a[i]>largest:
largest=a[i]
print ("Largest number:", largest)
它会产生以下的 输出 −
array('i', [10, 5, 15, 4, 6, 20, 9])
Largest number: 20
示例2
Python程序将一个数组中的所有偶数存储到另一个数组中 –
import array as arr
a = arr.array('i', [10,5,15,4,6,20,9])
print (a)
b = arr.array('i')
for i in range(len(a)):
if a[i]%2 == 0:
b.append(a[i])
print ("Even numbers:", b)
它将产生以下的 输出 –
array('i', [10, 5, 15, 4, 6, 20, 9])
Even numbers: array('i', [10, 4, 6, 20])
示例3
Python编程程序,找出Python数组中所有数字的平均数−
import array as arr
a = arr.array('i', [10,5,15,4,6,20,9])
print (a)
s = 0
for i in range(len(a)):
s+=a[i]
avg = s/len(a)
print ("Average:", avg)
# Using sum() function
avg = sum(a)/len(a)
print ("Average:", avg)
它将产生以下 输出 −
array('i', [10, 5, 15, 4, 6, 20, 9])
Average: 9.857142857142858
Average: 9.857142857142858