1.寫?個(gè)函數(shù)將?個(gè)指定的列表中的元素逆序(例如[1, 2, 3] -> [3, 2, 1])(注意:不要使?列表自帶的逆序函數(shù))
def list():
list1 = [1,2,3]
list2 = []
for _ in range(3):
list2.append(list1.pop())
print(list2)
list()
運(yùn)行結(jié)果:
[3, 2, 1]
2.寫?個(gè)函數(shù),提取出字符串中所有奇數(shù)位上的字符。
def str(str1):
for index in range(len(str1)):
if index % 2 == 0:
print(str1[index],end=' ')
str('1234567')
運(yùn)行結(jié)果:
1 3 5 7
3.寫?個(gè)匿名函數(shù),判斷指定的年是否是閏年
years = lambda x:'閏年' if x % 4 == 0 else '不是閏年'
print(years(2009))
運(yùn)行結(jié)果:
不是閏年
4.使?用遞歸打?。?/h1>
# n = 3的時(shí)候
# @
# @@@
# @@@@@
# n = 4的時(shí)候:
# @
# @@@
# @@@@@
# @@@@@@@
5.寫函數(shù),檢查傳?列表的長度,如果大于2,那么僅保留留前兩個(gè)長度的內(nèi)容,并將新內(nèi)容返回給調(diào)用者。
def list():
list1 = [7,2,3,4,5]
list2 = []
if len(list1) > 2:
for item in list1[0:2]:
list2.append(item)
print(list2)
list()
運(yùn)行結(jié)果:
[7, 2]
6.寫函數(shù),利用遞歸獲取斐波那契數(shù)列中的第 10 個(gè)數(shù),并將該值返回給調(diào)用者。
def num(n):
if n == 1 or n == 0:
return n
return num(n -1) + num(n - 2)
print(num(10))
運(yùn)行結(jié)果:
55
7.寫一個(gè)函數(shù),獲取列表中的成績的平均值,和最高分
def list():
sum1 = 0
list1 = [78,89,98,90,96]
list2 = list1[0]
for item in list1:
sum1 += item
if item > list2:
list2 = item
return sum1 / 4 , list2
print(list())
運(yùn)行結(jié)果:
(112.75, 98)
8.寫函數(shù),檢查獲取傳入列表或元組對象的所有奇數(shù)位索引對應(yīng)的元素,并將其作為新的列表返回給調(diào)用者。
def list():
list1 = [1,2,3,4,5,6,7,8,9]
list2 = []
for index in range(len(list1)):
if index % 2 != 0:
list2.append(list1[index])
print(list2)
list()
運(yùn)行結(jié)果:
[2, 4, 6, 8]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。