P06-计算列表数字的和
# Input:[1, 2, 3, 4] Output:10
# Input:[17, 5, 3, 5] Output:30
def sum_of_list(param_list):
total = 0
for item in param_list:
total += item
return total
list1 = [1, 2, 3, 4]
list2 = [17, 5, 3, 5]
print(f"sum of {list1}, ", sum_of_list(list1))
print(f"sum of {list2}, ", sum_of_list(list2))
import numpy as np
print(f"sum of {list1}, ", np.sum(list1))
print(f"sum of {list2}, ", np.sum(list2))
sum of [1, 2, 3, 4], 10
sum of [17, 5, 3, 5], 30
sum of [1, 2, 3, 4], 10
sum of [17, 5, 3, 5], 30
import numpy as np
ist1 = [1, 2, 3, 4]
list2 = [17, 5, 3, 5]
print(f"sum of {list1}, ", np.sum(list1))
print(f"sum of {list2}, ", np.sum(list2))
sum of [1, 2, 3, 4], 10
sum of [17, 5, 3, 5], 30
P07-计算数字范围中所有的偶数
'''
输入开始和结束值(不包含),得到所有偶数
偶数:能够被2所整除的整数,是2的倍数
输入:begin = 4, end = 15
返回:[4, 6, 8, 10, 12, 14]
'''
def get_even_numbers(begin, end):
result = []
for item in range(begin, end):
if item % 2 == 0:
result.append(item)
return result
bengin = 4
end = 15
print(f"begin = {begin}, end = {end}, even numbers: ",get_even_numbers(begin,end))
data = [item for item in range(begin, end)if item % 2 == 0] # 列表推导式
print(f"begin = {begin}, end = {end}, even numbers: ",data)
begin = 11, end = 15, even numbers: [12, 14]
begin = 11, end = 15, even numbers: [12, 14]
P08-移除列表中的多个元素
'''
输入:
原始列表:[3, 5, 7, 9, 11, 13]
移除元素:[7, 11]
返回:[3, 5, 9, 13]
'''
def remove_elements_from_list(lista, listb):
for item in listb:
lista.remove(item)
return lista
lista = [3, 5, 7, 9, 11, 13]
listb = [7, 11]
print(f"from {lista} remove {listb}, result: ",remove_elements_from_list(lista, listb))
lista = [3, 5, 7, 9, 11, 13]
listb = [7, 11]
data = [item for item in lista if item not in listb] #列表推导式
print(f"from {lista} remove {listb}, result: ",data)
from [3, 5, 7, 9, 11, 13] remove [7, 11], result: [3, 5, 9, 13]
from [3, 5, 7, 9, 11, 13] remove [7, 11], result: [3, 5, 9, 13]
P09-怎样对列表元素去重
'''
输入:包含重复元素的原始列表:[10, 20, 30, 10, 20]
返回:[10, 20, 30]
'''
def get_unique_list(lista):
result = []
for item in lista:
if item not in result:
result.append(item)
return result
lista = [10, 20, 30, 10, 20]
print(f"source list {lista}, unique list:", get_unique_list(lista))
# 利用set无重复元素
print(f"source list {lista}, unique list:", list(set(lista)))
source list [10, 20, 30, 10, 20], unique list: [10, 20, 30]
source list [10, 20, 30, 10, 20], unique list: [10, 20, 30]
P10-怎样对简单列表元素排序
'''
怎样对简单列表排序?
简单列表:元素类型不是复合类型(列表/元组/字典)
形式1:[20, 50, 10, 40, 30]
形式2:['bb', 'ee', 'aa', 'dd', 'cc']
知识点:
怎样原地排序?怎样不改变原列表排序?
怎样指定是升序还是降序排序?
'''
lista = [20, 50, 10, 40, 30]
listb = sorted(lista) # lista传入sorted函数,返回了一个新的list,传给了listb
lista.sort() # lista本身被改变了
print(f"lista is {lista}")
print(f"listb is {listb}")
listc = [20, 50, 10, 40, 30]
listd = sorted(listc, reverse = True) # 默认是升序
listc.sort(reverse = True) # reverse = False 是降序
print(f"listc is {listc}")
print(f"listd is {listd}")
lista is [10, 20, 30, 40, 50]
listb is [10, 20, 30, 40, 50]
listc is [50, 40, 30, 20, 10]
listd is [50, 40, 30, 20, 10]
蚂蚁学Python系列课程练习