Python之精心整理的50道入门练手习题 | Python技能树征题
生活随笔
收集整理的這篇文章主要介紹了
Python之精心整理的50道入门练手习题 | Python技能树征题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
① 已知一個字符串為 “hello_world_yoyo”,如何得到一個隊列 [“hello”,”world”,”yoyo”] ?
- 使用 split 函數(shù),分割字符串,并且將數(shù)據(jù)轉(zhuǎn)換成列表類型:
- 結(jié)果:
② 有個列表 [“hello”, “world”, “yoyo”],如何把列表里面的字符串聯(lián)起來,得到字符串 “hello_world_yoyo”?
- 使用 join 函數(shù)將數(shù)據(jù)轉(zhuǎn)換成字符串:
- 結(jié)果:
- 如果不依賴 python 提供的 join 方法,還可以通過 for 循環(huán),然后將字符串拼接,但是在用“+”連接字符串時,結(jié)果會生成新的對象,使用 join 時結(jié)果只是將原列表中的元素拼接起來,所以 join 效率比較高。for 循環(huán)拼接如下:
③ 把字符串 s 中的每個空格替換成”%20”,輸入:s = “We are happy.”,輸出:“We%20are%20happy.”。
- 使用 replace 函數(shù),替換字符換即可:
- 結(jié)果:
④ Python 如何打印 99 乘法表?
- for 循環(huán)打印:
- while 循環(huán)實現(xiàn):
- 結(jié)果:
⑤ 從下標 0 開始索引,找出單詞 “welcome” 在字符串“Hello, welcome to my world.” 中出現(xiàn)的位置,找不到返回 -1。
def test():message = 'Hello, welcome to my world.'world = 'welcome'if world in message:return message.find(world)else:return -1print(test())結(jié)果: 7⑥ 統(tǒng)計字符串“Hello, welcome to my world.” 中字母 w 出現(xiàn)的次數(shù)。
def test():message = 'Hello, welcome to my world.'# 計數(shù)num = 0# for 循環(huán) messagefor i in message:# 判斷如果 ‘w’ 字符串在 message 中,則 num +1if 'w' in i:num += 1return numprint(test())# 結(jié)果 2⑦ 輸入一個字符串 str,輸出第 m 個只出現(xiàn)過 n 次的字符,如在字符串 gbgkkdehh 中,找出第 2 個只出現(xiàn) 1 次的字符,輸出結(jié)果:d
def test(str_test, num, counts):""":param str_test: 字符串:param num: 字符串出現(xiàn)的次數(shù):param count: 字符串第幾次出現(xiàn)的次數(shù):return:"""# 定義一個空數(shù)組,存放邏輯處理后的數(shù)據(jù)list = []# for循環(huán)字符串的數(shù)據(jù)for i in str_test:# 使用 count 函數(shù),統(tǒng)計出所有字符串出現(xiàn)的次數(shù)count = str_test.count(i, 0, len(str_test))# 判斷字符串出現(xiàn)的次數(shù)與設(shè)置的counts的次數(shù)相同,則將數(shù)據(jù)存放在list數(shù)組中if count == num:list.append(i)# 返回第n次出現(xiàn)的字符串return list[counts-1]print(test('gbgkkdehh', 1, 2))結(jié)果: d⑧ 判斷字符串 a = “welcome to my world” 是否包含單詞 b = “world”,包含返回 True,不包含返回 False。
def test():message = 'welcome to my world'world = 'world'if world in message:return Truereturn Falseprint(test())結(jié)果: True⑨ 從 0 開始計數(shù),輸出指定字符串 A = “hello” 在字符串 B = “hi how are you hello world, hello yoyo!”中第一次出現(xiàn)的位置,如果 B 中不包含 A,則輸出 -1。
def test():message = 'hi how are you hello world, hello yoyo!'world = 'hello'return message.find(world)print(test())結(jié)果: 15⑩ 從 0 開始計數(shù),輸出指定字符串 A = “hello”在字符串 B = “hi how are you hello world, hello yoyo!”中最后出現(xiàn)的位置,如果 B 中不包含 A,則輸出 -1。
def test(string, str):# 定義 last_position 初始值為 -1last_position = -1while True:position = string.find(str, last_position+1)if position == -1:return last_positionlast_position = positionprint(test('hi how are you hello world, hello yoyo!', 'hello'))結(jié)果: 28? 給定一個數(shù) a,判斷一個數(shù)字是否為奇數(shù)或偶數(shù)。
while True:try:# 判斷輸入是否為整數(shù)num = int(input('輸入一個整數(shù):'))# 不是純數(shù)字需要重新輸入except ValueError: print("輸入的不是整數(shù)!")continueif num % 2 == 0:print('偶數(shù)')else:print('奇數(shù)')break結(jié)果: 輸入一個整數(shù):100 偶數(shù)? 輸入一個姓名,判斷是否姓王。
def test():user_input = input("請輸入您的姓名:")if user_input[0] == '王':return "用戶姓王"return "用戶不姓王"print(test())結(jié)果: 請輸入您的姓名:王總 用戶姓王? 如何判斷一個字符串是不是純數(shù)字組成?
- 利用 Python 提供的類型轉(zhuǎn)行,將用戶輸入的數(shù)據(jù)轉(zhuǎn)換成浮點數(shù)類型,如果轉(zhuǎn)換拋異常,則判斷數(shù)字不是純數(shù)字組成。
? 將字符串 a = “This is string example….wow!” 全部轉(zhuǎn)成大寫,字符串 b = “Welcome To My World” 全部轉(zhuǎn)成小寫。
a = 'This is string example….wow!' b = 'Welcome To My World'print(a.upper()) print(b.lower())? 將字符串 a = “ welcome to my world ”首尾空格去掉
- Python 提供了strip() 方法,可以去除首尾空格,rstrip() 去掉尾部空格,lstrip() 去掉首部空格,replace(" ", “”) 去掉全部空格。
- 還可以通過遞歸的方式實現(xiàn):
- 通過 while 循環(huán)實現(xiàn):
? 將字符串 s = “ajldjlajfdljfddd”,去重并從小到大排序輸出”adfjl”。
def test():s = 'ajldjlajfdljfddd'# 定義一個數(shù)組存放數(shù)據(jù)str_list = []# for循環(huán)s字符串中的數(shù)據(jù),然后將數(shù)據(jù)加入數(shù)組中for i in s:# 判斷如果數(shù)組中已經(jīng)存在這個字符串,則將字符串移除,加入新的字符串if i in str_list:str_list.remove(i)str_list.append(i)# 使用 sorted 方法,對字母進行排序a = sorted(str_list)# sorted方法返回的是一個列表,這邊將列表數(shù)據(jù)轉(zhuǎn)換成字符串return "".join(a)print(test())結(jié)果: adfjl? 打印出如下圖案(菱形):
def test():n = 8for i in range(-int(n/2), int(n/2) + 1):print(" "*abs(i), "*"*abs(n-abs(i)*2))print(test())結(jié)果:********************************? 給一個不多于 5 位的正整數(shù)(如 a = 12346),求它是幾位數(shù)和逆序打印出各位數(shù)字。
class Test:# 計算數(shù)字的位數(shù)def test_num(self, num):try:# 定義一個 length 的變量,來計算數(shù)字的長度length = 0while num != 0:# 判斷當(dāng) num 不為 0 的時候,則每次都除以10取整length += 1num = int(num) // 10if length > 5:return "請輸入正確的數(shù)字"return lengthexcept ValueError:return "請輸入正確的數(shù)字"# 逆序打印出個位數(shù)def test_sorted(self, num):if self.test_num(num) != "請輸入正確的數(shù)字":# 逆序打印出數(shù)字sorted_num = num[::-1]# 返回逆序的個位數(shù)return sorted_num[-1]print(Test().test_sorted('12346'))結(jié)果: 1? 如果一個 3 位數(shù)等于其各位數(shù)字的立方和,則稱這個數(shù)為水仙花數(shù)。例如:153 = 13 + 53 + 33,因此 153 就是一個水仙花數(shù)。那么如何求 1000 以內(nèi)的水仙花數(shù)(3 位數(shù))。
def test():for num in range(100, 1000):i = num // 100j = num // 10 % 10k = num % 10if i ** 3 + j ** 3 + k ** 3 == num:print(str(num) + "是水仙花數(shù)")test()? 求 1+2+3…+100 相加的和。
i = 1 for j in range(101):i = j + iprint(i)結(jié)果: 5051? 計算 1-2+3-4+5-…-100 的值。
def test(sum_to):# 定義一個初始值sum_all = 0# 循環(huán)想要計算的數(shù)據(jù)for i in range(1, sum_to + 1):sum_all += i * (-1) ** (1 + i)return sum_allif __name__ == '__main__':result = test(sum_to=100)print(result)-50? 現(xiàn)有計算公式 13 + 23 + 33 + 43 + …….+ n3,如何實現(xiàn):當(dāng)輸入 n = 5 時,輸出 225(對應(yīng)的公式 : 13 + 23 + 33 + 43 + 53 = 225)。
def test(n):sum = 0for i in range(1, n+1):sum += i*10+ireturn sumprint(test(5))結(jié)果: 225? 已知 a 的值為“hello”,b 的值為“world”,如何交換 a 和 b 的值,得到 a 的值為“world”,b 的值為”hello”?
a = 'hello' b = 'world'c = a a = b b = c print(a, b)? 如何判斷一個數(shù)組是對稱數(shù)組?
- 例如 [1,2,0,2,1],[1,2,3,3,2,1],這樣的數(shù)組都是對稱數(shù)組。
- 用 Python 判斷,是對稱數(shù)組打印 True,不是打印 False。
? 如果有一個列表 a = [1,3,5,7,11],那么如何讓它反轉(zhuǎn)成 [11,7,5,3,1],并且取到奇數(shù)位值的數(shù)字 [1,5,11]?
def test():a = [1, 3, 5, 7, 11]# 逆序打印數(shù)組中的數(shù)據(jù)print(a[::-1])# 定義一個計數(shù)的變量count = 0for i in a:# 判斷每循環(huán)列表中的一個數(shù)據(jù),則計數(shù)器中會 +1count += 1# 如果計數(shù)器為奇數(shù),則打印出來if count % 2 != 0:print(i)test()結(jié)果: [11, 7, 5, 3, 1] 1 5 11? 對列表 a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8] 中的數(shù)字從小到大排序。
a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8] print(sorted(a))結(jié)果: [1, 1, 6, 6, 7, 8, 8, 8, 8, 9, 11]? 找出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大值和最小值。
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] print(max(L1)) print(min(L1))結(jié)果: 88 1- 上面是通過 Python 自帶的函數(shù)實現(xiàn),如下,可以自己寫一個計算程序:
? 找出列表 a = [“hello”, “world”, “yoyo”, “congratulations”] 中單詞最長的一個。
def test():a = ["hello", "world", "yoyo", "congratulations"]# 統(tǒng)計數(shù)組中第一個值的長度length = len(a[0])for i in a:# 循環(huán)數(shù)組中的數(shù)據(jù),當(dāng)數(shù)組中的數(shù)據(jù)比初始值length中的值長,則替換掉length的默認值if len(i) > length:length = ireturn lengthprint(test())結(jié)果: congratulations? 取出列表 L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88] 中最大的三個值。
def test():L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]return sorted(L1)[:3]print(test())結(jié)果: [1, 2, 2]? 把列表 a = [1, -6, 2, -5, 9, 4, 20, -3] 中的數(shù)字絕對值從小到大排序。
def test():a = [1, -6, 2, -5, 9, 4, 20, -3]# 定義一個數(shù)組,存放處理后的絕對值數(shù)據(jù)lists = []for i in a:# 使用 abs() 方法處理絕對值lists.append(abs(i))return listsprint(test())結(jié)果: [1, 6, 2, 5, 9, 4, 20, 3]? 將 list = [“hello”, “helloworld”, “he”, “hao”, “good”] 里面的單詞按長度倒序。
def test():b = ["hello", "helloworld", "he", "hao", "good"]count = {}# 循環(huán)查看數(shù)組匯總每個字符串的長度for i in b:# 將數(shù)據(jù)統(tǒng)計稱字典格式,字符串作為鍵,字符串長度作為值count[i] = len(i)# 按照字典的值,將字典數(shù)據(jù)從大到小排序message = sorted(count.items(), key=lambda x:x[1], reverse=True)lists = []for j in message:# 循環(huán)把處理后的數(shù)據(jù),加入到新的數(shù)組中lists.append(j[0])print(lists)test()結(jié)果: ['helloworld', 'hello', 'good', 'hao', 'he']? L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88],如何用一行代碼得出 [1, 2, 3, 5, 11, 33, 88]。
print(sorted(set(L1)))結(jié)果: [1, 2, 3, 5, 11, 33, 88]? 將列表中的重復(fù)值取出(僅保留第一個),要求保留原始列表順序,如 a = [3, 2, 1, 4, 2, 6, 1],輸出 [3, 2, 1, 4, 6]。
a = [3, 2, 1, 4, 2, 6, 1]lists = [] for i in a:if i not in lists:lists.append(i) print(lists)結(jié)果: [3, 2, 1, 4, 6]? a = [1, 3, 5, 7],b = [‘a(chǎn)’, ‘b’, ‘c’, ‘d’],如何得到 [1, 3, 5, 7, ‘a(chǎn)’, ‘b’, ‘c’, ‘d’]。
a = [1, 3, 5, 7] b = ['a', 'b', 'c', 'd']for i in b:a.append(i)print(a)結(jié)果: [1, 3, 5, 7, 'a', 'b', 'c', 'd']? 用一行代碼生成一個包含 1-10 之間所有偶數(shù)的列表。
print([i for i in range(2, 11, 2) if i % 2 == 0])結(jié)果: [2, 4, 6, 8, 10]? 列表 a = [1,2,3,4,5],計算列表成員的平方數(shù),得到 [1,4,9,16,25]。
a = [1, 2, 3, 4, 5] lists = []for i in a:lists.append(i*i)print(lists)結(jié)果: [1, 4, 9, 16, 25]? 使用列表推導(dǎo)式,將列表中 a = [1, 3, -3, 4, -2, 8, -7, 6],找出大于 0 的數(shù),重新生成一個新的列表。
a = [1, 3, -3, 4, -2, 8, -7, 6]print([i for i in a if i > 0])結(jié)果: [1, 3, 4, 8, 6]? 統(tǒng)計在一個隊列中的數(shù)字,有多少個正數(shù),多少個負數(shù),如 [1, 3, 5, 7, 0, -1, -9, -4, -5, 8]。
def test():lists = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8]# 定義一個變量,計算正數(shù)positive_num = 0# 計算負數(shù)negative_num = 0for i in lists:# 判斷循環(huán)數(shù)組中的數(shù)據(jù)大于0,則正數(shù)會+1if i > 0:negative_num += 1# 因為 0 既不是正數(shù)也不是負數(shù),所以我們判斷小于0為負數(shù)elif i < 0:positive_num += 1 return positive_num, negative_numprint(test())結(jié)果: (4, 5)? a = [“張三”,”張四”,”張五”,”王二”],如何刪除姓張的?
def test():a = ["張三", "張四", "張五", "王二"]for i in a[:]:if i[0] == '張':a.remove(i)return aprint(test())結(jié)果: ['王二']? 有個列表 a = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8],使用 filter 函數(shù)過濾出大于 0 的數(shù)。
a = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8]def test(a):return a < 0temlists = filter(test, a) print(list(temlists))結(jié)果: [-1, -9, -4, -5]? 列表 b = [“張三”, “張四”, “張五”, “王二”],過濾掉姓張的姓名。
b = ["張三", "張四", "張五", "王二"]def test(b):return b[0] != '張'print(list(filter(test, b)))結(jié)果: ['王二']? 過濾掉列表中不及格的學(xué)生,a = [{“name”: “張三”, “score”: 66},{“name”: “李四”, “score”: 88},{“name”: “王五”, “score”: 90},{“name”: “陳六”, “score”: 56}]。
a = [{"name": "張三", "score": 66},{"name": "李四", "score": 88},{"name": "王五", "score": 90},{"name": "陳六", "score": 56} ]print(list(filter(lambda x: x.get("score") >= 60, a)))返回: [{'name': '張三', 'score': 66}, {'name': '李四', 'score': 88}, {'name': '王五', 'score': 90}]? 有個列表 a = [1, 2, 3, 11, 2, 5, 88, 3, 2, 5, 33],找出列表中最大的數(shù),出現(xiàn)的位置,下標從 0 開始。
def test():a = [1, 2, 3, 11, 2, 5, 88, 3, 2, 5, 33]# 找到數(shù)組中最大的數(shù)字b = max(a)count = 0# 定義一個計數(shù)器,每次循環(huán)一個數(shù)字的時候,則計數(shù)器+1,用于記錄數(shù)字的下標for i in a:count += 1# 判斷當(dāng)循環(huán)到最大的數(shù)字時,則退出if i == b:breakreturn count -1print(test()) 結(jié)果: 6? 給定一個整數(shù)數(shù)組 A 及它的大小 n,同時給定要查找的元素 val,請返回它在數(shù)組中的位置(從 0 開始),若不存在該元素,返回 -1。若該元素出現(xiàn)多次請返回第一個找到的位置,如 A1 = [1, “aa”, 2, “bb”, “val”, 33] 或 A2 = [1, “aa”, 2, “bb”]。
def test(lists, string):""":param lists: 數(shù)組:param string: 查找的字符串:return: """# 判斷字符串不再數(shù)組中,返回-1if string not in lists:return -1count = 0# 獲取字符串當(dāng)前所在的位置for i in lists:count += 1if i == string:return count - 1print(test([1, "aa", "val", 2, "bb", "val", 33], 'val'))結(jié)果: 2? 給定一個整數(shù)數(shù)組 nums 和一個目標值 target ,請在該數(shù)組中找出和為目標值的那兩個整數(shù),并返回它們的數(shù)組下標。可以假設(shè)每種輸入只會對應(yīng)一個答案,但是數(shù)組中同一個元素不能使用兩遍。示例:給定 nums = [2,7,11,15],target = 9,因為 nums[0] + nums[1] = 2+7 = 9,所以返回 [0,1]。
def test(target=9):num = [2, 7, 11, 15]# 統(tǒng)計數(shù)組的長度length = len(num)dicts = {}for i in range(length):# 添加兩個 for 循環(huán),第二次for循環(huán)時,循環(huán)的位置會比第一次循環(huán)多一次for j in range(i + 1, length):# 將循環(huán)后的數(shù)據(jù)放在列表中,利用字典 key 唯一的屬性處理數(shù)據(jù)dicts.update({num[i] + num[j]: {i, j}})# 打印出來的數(shù)據(jù),是元素的格式,按照題目,將數(shù)據(jù)轉(zhuǎn)行成字典lists = []for nums in dicts[target]:lists.append(nums)return listsprint(test())結(jié)果: [0, 1]? a = [[1,2],[3,4],[5,6]] 如何一句代碼得到 [1, 2, 3, 4, 5, 6]。
a = [[1, 2], [3, 4], [5, 6]]# 定義一個新數(shù)組存放數(shù)據(jù) lists = []for i in a:# 二次 for 循環(huán),將數(shù)據(jù)存入到 lists 中for j in i:lists.append(j)print(lists)結(jié)果: [1, 2, 3, 4, 5, 6]? 二維數(shù)組取值(矩陣),有 a = [[“A”, 1], [“B”, 2]] ,如何取出 2。
import numpya = [["A", 1], ["B", 2]]x = numpy.array(a) print(x[1, 1])結(jié)果: 2總結(jié)
以上是生活随笔為你收集整理的Python之精心整理的50道入门练手习题 | Python技能树征题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS之性能优化·列表异步绘制
- 下一篇: Python之打造专属Python开发者