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