50 道 Python 基础练习题(附答案详解)
生活随笔
收集整理的這篇文章主要介紹了
50 道 Python 基础练习题(附答案详解)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
作者:Amo Xiang
https://blog.csdn.net/xw1680/article/details/103546693
1.兩個變量的交換
# -*- coding: utf-8 -*-
# @Time : 2019/12/14 23:30
# @Author : 我就是任性-Amo
# @FileName: 1.兩個變量的交換.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/xw1680# 需求: 完成兩個變量值的交換
# 如:a=20,b=30-->a=30,b=20
a = 20
b = 30
print(f"變量交換之前a的值為{a},b的值為{b}")
# 第一種交換變量的方式: 使用第三方臨時變量
temp = a # 先將a值賦值給一個第三變量 存儲a的值
a = b # 將b的值賦值給a
b = temp # 將temp的值賦值給b temp存儲的值其實為原來變量a存儲的值
print(f"變量交換之后a的值為{a},b的值為{b}")# 第二種交換變量的方式: 使用python特有的方式
a, b = b, a
print(f"變量交換之后a的值為{a},b的值為{b}")# 第三種交換變量的方式: 使用算術運算符的方式
# 總的來說: 無論a,b如何交換 他們的和都是不變的
a = a + b
b = a - b
a = a - b
print(f"變量交換之后a的值為{a},b的值為{b}")# 第四種交換變量的方式: 使用位運算符的方式
a = a ^ b
b = a ^ b
a = a ^ b
print(f"變量交換之后a的值為{a},b的值為{b}")# 在java中還可以使用下面這種方式:
# int a = 10;
# int b = 20;
# System.out.println("交換變量前a的值為:" + a + ",b的值為:" + b);
# a = (a + b) - (b = a);
#?System.out.println("交換變量后a的值為:"?+?a?+?",b的值為:"?+?b);
程序運行結果如下:
2.有四個數(shù)字:1、2、3、4,能組成多少個互不相同且無重復數(shù)字的三位數(shù)?各是多少?
# -*- coding: utf-8 -*- # @Time : 2019/12/14 23:47 # @Author : 我就是任性-Amo # @FileName: 2.數(shù)字1-4組成不同且不重復的三位數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目:有四個數(shù)字:1、2、3、4,能組成多少個互不相同且無重復數(shù)字的三位數(shù)?各是多少? count = 0 # 計數(shù)器 for i in range(1, 5): # 百位的數(shù)字可以是1,2,3,4for j in range(1, 5):for k in range(1, 5):# 百位 十位 個位的數(shù)字不重復if i != j and i != k and j != k:count += 1 # 符合條件計數(shù)器就+1print(i * 100 + j * 10 + k) # 打印符合條件的三位數(shù)print(count)??#?打印符合條件的三位數(shù)的個數(shù)程序運行結果如下:
3.求應發(fā)獎金數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/15 00:04 # @Author : 我就是任性-Amo # @FileName: 3.求應發(fā)獎金數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 需求: 企業(yè)發(fā)放的獎金根據(jù)利潤提成。從鍵盤輸入當月利潤I,求應發(fā)放獎金總數(shù)? # 利潤(i)低于或等于10萬元時,獎金可提10%; # 利潤高于10萬元,低于20萬元時,低于10萬元的部分按10%提成,高于10萬元的部分,可提成7.5%; # 20萬到40萬之間時,高于20萬元的部分,可提成5%; # 40萬到60萬之間時高于40萬元的部分,可提成3%; # 60萬到100萬之間時,高于60萬元的部分,可提成1.5% # 高于100萬元時,超過100萬元的部分按1%提成profit = [1000000, 600000, 400000, 200000, 100000, 0] # 利潤 rate = [0.01, 0.015, 0.03, 0.05, 0.075, 0.1] # 利率 bonus = 0 # 獎金 # 鍵盤錄入當月的利潤i i = int(input(">>>:"))for j in range(6):if i > profit[j]:bonus += (i - profit[j]) * rate[j] # 減去基本數(shù) 再計算獎金i = profit[j] # 下次計算的利潤值 print(bonus)程序運行結果如下:
4.輸入某年某月某日,判斷這一天是這一年的第幾天?
# -*- coding: utf-8 -*- # @Time : 2019/12/15 00:39 # @Author : 我就是任性-Amo # @FileName: 4.判斷用戶輸入的是這一年的第幾天.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 需求:輸入某年某月某日,判斷這一天是這一年的第幾天? # 思路:以5月20日為例,應該先把前四個月的加起來,然后再加上20天即本年的第幾天 # 特殊情況就是: 如果年份為閏年且輸入月份大于2時需考慮多加一天year = int(input("年:")) month = int(input("月:")) day = int(input("日:")) sum_day = 0 # 第幾天 leap_year = 0 # 閏年# 使用元組定義天數(shù) # 如果輸入的月份是1月份,則直接計算day即可 # 如果輸入的月份是2月份,則要先計算出1月份的天數(shù),即為31天 # 以此類推 # 1 2 3 4 5 6 7 8 9 10 11 12 # 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334) # 根據(jù)輸入的月份,計算出前幾個月的天數(shù) if 0 < month <= 12:sum_day = months[month - 1] else:print("輸入的月份有誤") # 判斷是否為閏年: # 1.能被400整除 或者是 2.能被4整除并且不能被100整除 if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):# 如果是閏年 則將leap_year變?yōu)?leap_year = 1# 判斷如果是閏年并且輸入的月份大于2則在總的天數(shù)上加1 if leap_year == 1 and month > 2:sum_day += day + 1 else:sum_day += dayprint(f"it?is?the?{sum_day}th?day.")??#?打印程序運行結果如下:
5.輸入三個整數(shù)x,y,z,請把這三個數(shù)由小到大輸出
# -*- coding: utf-8 -*- # @Time : 2019/12/15 01:06 # @Author : 我就是任性-Amo # @FileName: 5.輸入三個整數(shù),由小到大輸出.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目:輸入三個整數(shù)x,y,z,請把這三個數(shù)由小到大輸出。# 1.錄入數(shù)據(jù) x = int(input(">>>:")) y = int(input(">>>:")) z = int(input(">>>:"))# 2.使用列表存儲數(shù)據(jù)并進行排序 num_list = [x, y, z] num_list.sort() print(num_list)程序運行結果如下:
6.斐波那契數(shù)列
# -*- coding: utf-8 -*- # @Time : 2019/12/15 01:33 # @Author : 我就是任性-Amo # @FileName: 6.斐波那契數(shù)列.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目:斐波那契數(shù)列 # 程序分析: 斐波那契數(shù)列(Fibonacci sequence),又稱黃金分割數(shù)列,指的是這樣一個數(shù)列: # 1 1 2 3 5 8 13 21 34 55....# 第一種方式:使用函數(shù) def fibonacci1(n):a = 0b = 1for i in range(n):a, b = b, a + bprint(f"斐波那契數(shù)列第{n}項的值為:{a}")fibonacci1(3) # 2# 第二種方式:使用遞歸 def fibonacci2(n):if n == 1 or n == 2:return 1else:return fibonacci2(n - 1) + fibonacci2(n - 2)print(fibonacci2(10)) # 3# 第三種方式:輸出指定個數(shù)的斐波那契數(shù)列 def fibonacci3(n):fibs = [1, 1]if n == 1:return [1]if n == 2:return [1, 1]for i in range(2, n):fibs.append(fibs[-1] + fibs[-2]) # 列表的最后兩個數(shù)字相加return fibsprint(fibonacci3(10))# 第四種方式: 使用生成器的方式實現(xiàn) def fibonacci4(n):a = 0b = 1for i in range(0, n):a, b = b, a + byield aprint("amo~")f = fibonacci4(4) print(f) # <generator object fibonacci4 at 0x101cc63d0> print(next(f)) # 相當于去調用內置方法__next__ -->1 print(f.__next__()) # 1 print(f.__next__()) # 2 print(f.__next__())??#?3程序運行結果如下:
7. 將一個列表的數(shù)據(jù)復制到另一個列表中
# -*- coding: utf-8 -*- # @Time : 2019/12/15 02:15 # @Author : 我就是任性-Amo # @FileName: 7.將一個列表的數(shù)據(jù)復制到另一個列表中.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680list1 = [1, 2, 3, 4, 5] print(list1) # 1.直接使用列表的copy方法 new_list1 = list1.copy() print(new_list1) # 2.使用列表的切片 new_list2 = list1[:] print(new_list2)程序運行結果如下:
8.輸出九九乘法表
# -*- coding: utf-8 -*- # @Time : 2019/12/15 02:20 # @Author : 我就是任性-Amo # @FileName: 8.輸出 9*9 乘法口訣表.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 分析: 九九乘法表的每一個小的單元類似為: 1 * 1 = 1 # print("1 * 1 = 1") # 只是里面的1隨著行數(shù)在不停的變化 而等號后面的結果根據(jù)前面的數(shù)字動態(tài)生成 # print("2 * 1 = 2", end="\t") # print("2 * 2 = 4") # print("3 * 1 = 3", end="\t") # print("3 * 2 = 6", end="\t") # print("3 * 3 = 9")# 綜上: 發(fā)現(xiàn)規(guī)律第一個數(shù)字從1變化到9 第二個數(shù)字最多變化到和第一個數(shù)字相等 最后的數(shù)字為前兩個數(shù)字的積for i in range(1, 10): # 第一個數(shù)字的變化范圍for j in range(1, i + 1): # 第二個數(shù)字變化的范圍print(f"{i} * {j} = {i * j}", end="\t")# 循環(huán)完成之后需要進行換行print()程序運行結果如下:
9.判斷101-200之間有多少個素數(shù),并輸出所有素數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/15 10:32 # @Author : 我就是任性-Amo # @FileName: 9.判斷101-200之間有多少個素數(shù),并輸出所有素數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 判斷101-200之間有多少個素數(shù),并輸出所有素數(shù)。 # 分析: # 1.數(shù)據(jù)變化的范圍是從101-200 所以需要使用循環(huán) # 2.素數(shù): 只能被1和本身整除的數(shù) 所以需要一個變量從1變到本身 # 3.判斷: 如果有一個非1和本身的數(shù)被整除 則跳出循環(huán) 判斷下一個數(shù)字 # 如果循環(huán)完成,都只有1和本身能被整除 說明符合條件 計數(shù)器+1# 定義一個變量為計數(shù)器 count = 0 # 第一種方式: 使用while循環(huán)實現(xiàn) i = 101 while i <= 200:j = 2# 其實這里的話是可以進行優(yōu)化的 只需要判斷數(shù)字的一半次數(shù)就可以了# 因為數(shù)字就是等于兩個數(shù)的乘積 判斷了前一個數(shù) 后一個數(shù)肯定就不用判斷了# 數(shù)字的乘積就是一個小的數(shù)字*大的數(shù)字 減少循環(huán)的次數(shù)# while j < i:while j < i / 2:if i % j == 0:breakj += 1else:count += 1print(i)i += 1 print(f"The total is {count}") count = 0 # 第二種方式: 使用for循環(huán)改寫 for i in range(101, 201):# for j in range(2, i):for j in range(2, int(i / 2)): # 優(yōu)化循環(huán)次數(shù)if i % j == 0:breakelse:count += 1print(i) print(f"The?total?is?{count}")程序運行結果如下:
10.打印水仙花數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/15 10:54 # @Author : 我就是任性-Amo # @FileName: 10.打印水仙花數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目:打印出所有的"水仙花數(shù)",所謂"水仙花數(shù)"是指一個三位數(shù),其各位數(shù)字立方和等于該數(shù)本身。 # 例如:153是一個"水仙花數(shù)",因為153=1的三次方+5的三次方+3的三次方 # 程序分析:利用for循環(huán)控制100-999個數(shù),每個數(shù)分解出個位,十位,百位 # 核心: 就是如何獲取到每個位上的數(shù)字 # 例子: 12345 # 個位: 12345 % 10 # 十位: 12345 // 10 % 10 # 百位: 12345 // 100 % 10 # 千位: 12345 // 1000 % 10 # 萬位: 12345 // 10000# 1.三位數(shù)的范圍為:100~999 所以需要使用循環(huán) for i in range(100, 1000):# 2.根據(jù)水仙花數(shù)的概念去判斷ge_wei = i % 10shi_wei = i // 10 % 10bai_wei = i // 100if i == (ge_wei ** 3 + shi_wei ** 3 + bai_wei ** 3):print(i)程序運行結果如下:
11.將一個正整數(shù)分解質因數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/15 11:07 # @Author : 我就是任性-Amo # @FileName: 11.將一個正整數(shù)分解質因數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 將一個正整數(shù)分解質因數(shù)。例如:輸入90,打印出90=2*3*3*5。 # 程序分析:對n進行分解質因數(shù),應先找到一個最小的質數(shù)k,然后按下述步驟完成: # (1)如果這個質數(shù)恰等于n,則說明分解質因數(shù)的過程已經結束,打印出即可。 # (2)如果n<>k,但n能被k整除,則應打印出k的值,并用n除以k的商,作為新的正整數(shù)n,重復執(zhí)行第一步。 # (3)如果n不能被k整除,則用k+1作為k的值,重復執(zhí)行第一步# 第一種方式實現(xiàn): 使用循環(huán) # while True: # 可以不停的進行錄入數(shù)據(jù) 進行分解質因數(shù) # num = int(input(">>>:")) # print(f"{num}=", end="") # while num > 1: # 如果商小于等于1 則沒有必要再進行循環(huán) # for j in range(2, num + 1): # if num % j == 0: # num = int(num / j) # if num == 1: # print(f"{j}", end="") # else: # print(f"{j}*", end="") # break # 如果有一個滿足條件能被整除 這里一定要跳出循環(huán) 從2開始再次進行判斷 # print() # 換行# 第二種方式實現(xiàn): 使用遞歸 def dec_prime_factor(num):# 遞歸終止條件if num == 1:return []else:for i in range(2, num + 1):# divmod()函數(shù): 返回的是一個元組# 元組第一個元素為商,第二個元素為余數(shù)# merchant: 商 remainder: 余數(shù)merchant, remainder = divmod(num, i)if remainder == 0:# 列表的合并 將幾個列表中的元素整合到一個列表中return [i] + dec_prime_factor(merchant)while True:number = int(input(">>>:"))print(f"{number}=", end="")prime_list = dec_prime_factor(number)# 這里一定要先是用map函數(shù)將列表中的每一個數(shù)字轉換成字符串類型 才能使用join去拼接prime_list_str = "*".join(map(str, prime_list))print(prime_list_str)程序運行結果如下:
12.條件運算符練習
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:05 # @Author : 我就是任性-Amo # @FileName: 12.條件運算符練習.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 利用條件運算符的嵌套來完成此題: # 學習成績>=90分的同學用A表示,60-89分之間的用B表示,60分以下的用C表示while True:score = int(input(">>>:"))# 值1 if 條件表達式 else 值2# 條件表達式成立返回值1,否則返回值2score_grade = 'A' if score >= 90 else 'B' if 60 <= score <= 89 else 'C'print(score_grade)程序運行結果如下:
13.輸入一行字符,分別統(tǒng)計出其中英文字母、空格、數(shù)字和其它字符的個數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:18 # @Author : 我就是任性-Amo # @FileName: 13.統(tǒng)計字符個數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680 import res = input("請輸入一個字符串:").strip() letters = 0 space = 0 digit = 0 other = 0 # 1.方式1使用for循環(huán) while循環(huán)也一樣 for i in s:if i.isalpha(): # 判斷是否是字母letters += 1elif i.isspace(): # 判斷是否是空白字符space += 1elif i.isdigit(): # 判斷是否是數(shù)字digit += 1else:other += 1print(f'char = {letters},space = {space},digit = {digit},others = {other}')# 2.使用正則表達式 letters = len("".join(re.findall(r"[a-zA-Z]", s))) # 匹配字母 space = len("".join(re.findall(r"\s+", s))) # 匹配空白字符 digit = len("".join(re.findall(r"\d+", s))) # 匹配數(shù)字 # 匹配非字母 數(shù)字 下劃線 此時空白字符也會被匹配到 所以先要將空白字符移除 other_list = re.findall(r"\W", s) for i in other_list:if i.isspace:other_list.remove(i) other = len("".join(other_list)) print(f'char?=?{letters},space?=?{space},digit?=?{digit},others?=?{other}')程序運行結果如下:
14.求s=a+aa+aaa+aaaa+aa…a的值
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:46 # @Author : 我就是任性-Amo # @FileName: 14.求s=a+aa+aaa+aaaa+aa...a的值.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數(shù)字 # 例如2+22+222+2222+22222(此時共有5個數(shù)相加),幾個數(shù)相加由鍵盤控制 # 24690# 1.輸入幾個數(shù)相加以及要相加的數(shù)字 num = input("請輸入數(shù)字:") count = int(input("請輸入相加的個數(shù):")) get_sum = 0 # 統(tǒng)計和 str_list = [] for i in range(1, count + 1):# 將每個元素存入到列表中 用于后面的結果拼接str_list.append(str(num * i))# 累加get_sum += int(num * i)# 拼接:24690=2+22+222+2222+22222 print(f"{get_sum}={'+'.join(str_list)}")程序運行結果如下:
15.編程找出1000以內的所有完數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:48 # @Author : 我就是任性-Amo # @FileName: 15.求完全數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目:一個數(shù)如果恰好等于它的因子之和,這個數(shù)就稱為"完數(shù)"。例如6=1+2+3.編程找出1000以內的所有完數(shù) for i in range(1, 1000):num_list = []for k in range(1, i):if i % k == 0:num_list.append(k)if sum(num_list) == i:str1 = "+".join(map(str, num_list))print(f"{i}={str1}")程序運行結果如下:
16.自由落體
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:50 # @Author : 我就是任性-Amo # @FileName: 16.自由落體練習.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 一球從100米高度自由落下,每次落地后反跳回原高度的一半 # 再落下,求它在第10次落地時,共經過多少米?第10次反彈多高? tour = [] height = [] hei = 100 # 起始高度 tim = 10 # 次數(shù) for i in range(1, tim + 1):# 從第二次開始,落地時的距離應該是反彈高度乘以2(彈到最高點再落下)if i == 1:tour.append(hei)else:tour.append(2 * hei)hei /= 2height.append(hei)print(f"總高度: tour = {sum(tour)}") print(f"第10次反彈高度:?height?=?{height[-1]}")程序運行結果如下:
17.猴子吃桃問題
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:51 # @Author : 我就是任性-Amo # @FileName: 17.猴子吃桃.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 猴子吃桃問題:猴子第一天摘下若干個桃子,當即吃了一半,還不過癮, # 又多吃了一個第二天早上又將剩下的桃子吃掉一半,又多吃了一個。以后每天早上都吃了前一天剩下的一半零一個。 # 到第10天早上想再吃時,見只剩下一個桃子了。求第一天共摘了多少。peach = 1 # 定義第10天的桃子數(shù) # 第九天的桃子數(shù)=(第十天的桃子數(shù)+1)*2 for i in range(10, 1, -1):peach = (peach + 1) * 2print(f"第{i?-?1}天的桃子數(shù)量為:?{peach}")程序運行結果如下:
18.打印菱形
分析:如下圖所示
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:53 # @Author : 我就是任性-Amo # @FileName: 18.打印菱形.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 打印菱形 # 簡單理解可以理解為一個正等腰三角形和倒等腰三角形組成 # * # *** # ***** # ******* # ********* # ******* # ***** # *** # * # 1.打印上三角形 for i in range(1, 11, 2):print(" " * int((9 - i) // 2) + "*" * i)# 2.打印下三角形 for j in range(7, 0, -2):print("?"?*?int((9?-?j)?//?2)?+?"*"?*?j)程序運行結果如下:
19.有一分數(shù)序列:2/1,3/2,5/3,8/5,13/8,21/13…求出這個數(shù)列的前20項之和
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:54 # @Author : 我就是任性-Amo # @FileName: 20.求1+2!+3!+...+20!的和.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680from functools import reduce# 題目: 求1+2!+3!+...+20!的和 # 第一種方式: 使用循環(huán) num = int(input("請輸入num:")) get_sum = 0 # 統(tǒng)計和 cheng_ji = 1 for j in range(1, num + 1):cheng_ji *= jget_sum += cheng_ji print(f"1+2!+3!+...+{num}!={get_sum}") # 拼接字符串可以優(yōu)化# 第二種方式: 使用高階函數(shù)map L = range(1, num + 1)# 定義一個求一個數(shù)的階乘的函數(shù) def operate(x):r = 1for i in range(1, x + 1):r *= ireturn rs = sum(map(operate, L)) print(f"1+2!+3!+...+{num}!={s}")程序運行結果如下:
21.利用遞歸方法求5!
# -*- coding: utf-8 -*- # @Time : 2019/12/15 12:55 # @Author : 我就是任性-Amo # @FileName: 21.遞歸求5的階乘.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 利用遞歸方法求5! def fact(num):if num == 1:return 1else:return num * fact(num - 1)print(fact(5))程序運行結果如下:
22.判斷一個數(shù)是否是回文數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/15 23:48 # @Author : 我就是任性-Amo # @FileName: 22.判斷一個數(shù)字是否是回文數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 一個5位數(shù),判斷它是不是回文數(shù)。即12321是回文數(shù),個位與萬位相同,十位與千位相同 # 思路1: 獲取到各個位上的數(shù)字 然后按照回文數(shù)的概念進行比較 num1 = int(input(">>>:")) ge_wei = num1 % 10 shi_wei = num1 // 10 % 10 qian_wei = num1 // 1000 % 10 wan_wei = num1 // 10000 if ge_wei == wan_wei and shi_wei == qian_wei:print(f"{num1}是回文數(shù)") else:print(f"{num1}不是回文數(shù)") # 思路2: 逆序后的數(shù)字與原來的數(shù)字比較 num2 = input(">>>:") new_num2 = num2[::-1] if num2 == new_num2:print(f"{num2}是回文數(shù)") else:print(f"{num2}不是回文數(shù)") # 思路3: 通過字符串的操作判斷個位與萬位相同,十位與千位相同 num3 = input(">>>:") flag = True # 用來判斷是否為回文數(shù) for i in range(int(len(num3) / 2)):if num3[i] != num3[-i - 1]:flag = Falsebreak if flag:print(f"{num3}是回文數(shù)") else:print(f"{num3}不是回文數(shù)")程序運行結果如下:
23.兩個矩陣相加
# -*- coding: utf-8 -*- # @Time : 2019/12/16 00:11 # @Author : 我就是任性-Amo # @FileName: 23.求兩個矩陣的和.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目:兩個3行3列的矩陣,實現(xiàn)其對應位置的數(shù)據(jù)相加,并返回一個新矩陣 # 程序分析:創(chuàng)建一個新的3行3列的矩陣,使用for迭代并取出X和Y矩陣中對應位置的值,相加后放到新矩陣的對應位置中 X = [[12, 7, 3],[4, 5, 6],[7, 8, 9]]Y = [[5, 8, 1],[6, 7, 3],[4, 5, 9]]result = [[0, 0, 0],[0, 0, 0],[0, 0, 0]] # 初始化結果for i in range(len(X)): # 迭代三次 拿到每一個列表for j in range(len(X[0])): # 拿到列表中的元素result[i][j] = X[i][j] + Y[i][j]for i in result:print(i)程序運行結果如下:
24.統(tǒng)計1-100的和
# -*- coding: utf-8 -*- # @Time : 2019/12/16 00:19 # @Author : 我就是任性-Amo # @FileName: 24.統(tǒng)計1-100的和.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目:統(tǒng)計1到100 之和。 get_sum = 0 for i in range(1, 101):get_sum += iprint("1-100的和為:?%d"?%?get_sum)程序運行結果如下:
25.三級菜單
# -*- coding: utf-8 -*- # @Time : 2019/11/11 09:17 # @Author : 我就是任性-Amo # @FileName: 02_three_level_menu.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 初始化數(shù)據(jù) menu = {'北京': {'海淀': {'五道口': {'soho': {},'網易': {},'google': {}},'中關村': {'愛奇藝': {},'汽車之家': {},'youku': {},},'上地': {'百度': {},},},'昌平': {'沙河': {'老男孩': {},'北航': {},},'天通苑': {},'回龍觀': {},},'朝陽': {},'東城': {},},'上海': {'閔行': {"人民廣場": {'炸雞店': {}}},'閘北': {'火車站': {'攜程': {}}},'浦東': {},},'山東': {}, }# 使用死循環(huán)保持程序可以不停地進行錄入 然后根據(jù)指定的條件退出循環(huán) current_level = menu # 當前菜單層 layer_list = [] # 存儲之前的菜單層 列表有序 while True:for city in current_level:print(city)choice = input(">>:").strip() # 去除空白字符if choice in current_level: # 判斷選擇城市是否在字典中l(wèi)ayer_list.append(current_level) # 使用列表存儲上層菜單current_level = current_level[choice] # 當前菜單更改為下層菜單elif choice == "b": # 用戶輸入的為b的時候 表示回退上一層if current_level == menu: # 判斷是否是頂層print("reach top level")continueelse:current_level = layer_list.pop() # 回退elif choice == "q":exit("bye~")程序運行結果如下:
26.雙色球
""" 作業(yè):雙色球選購 1 雙色球(假設一共八個球,6個紅球,球號1-32、2個藍球,球號1-16) 2 確保用戶不能重復選擇,不能超出范圍 3 用戶輸入有誤時有相應的錯誤提示 4 最后展示用戶選擇的雙色球的號碼 """ # 沒有卡輸入的內容為空時的情況 print("Welcome to 小猿圈 lottery station")red_ball_list = [] # 用于存儲選中的紅球號 blue_ball_list = [] # 用于存儲選中的藍球號 i = 1 # 提示用戶輸入紅球號時候帶編號 [1] [2] j = 1 # 提示用戶輸入藍球號時候帶編號 [1] [2]# 用戶一直在選 所以采用死循環(huán) while True:# 判斷紅球號是否已經有效選擇6次 如果是則開始選籃球號if len(red_ball_list) == 6:# 籃球號選擇有效的2次 則退出循環(huán)if len(blue_ball_list) == 2:breakblue_ball_str = input("\033[34m["+str(j)+"]select blue ball:"+"\033[0m")blue_ball_num = 0 # 初始化值# 判斷是否輸入的內容是否為空或者是輸入的是字母if blue_ball_str.isdigit():blue_ball_num = int(blue_ball_str)if 1 <= blue_ball_num <= 16:if blue_ball_num not in blue_ball_list:blue_ball_list.append(blue_ball_num)j += 1else:print(f"number {blue_ball_num} is already exist in blue ball list")else:print("only can select n between 1-16")else:print("only can input num")else:red_ball_str = input("\033[31m[" + str(i) + "]select red ball" + "\033[0m:")if red_ball_str.isdigit():red_ball_num = int(red_ball_str)if 1 <= red_ball_num <= 32:if red_ball_num not in red_ball_list:red_ball_list.append(red_ball_num)i += 1else:print(f"number {red_ball_num} is already exist in red ball list")else:print("only can select n between 1-32")else:print("only can input num") print() print() print("Red ball:", red_ball_list) print("Blue ball:", blue_ball_list) print("Good?Luck.")程序運行結果如下:
27.股票查詢接口
# -*- coding: utf-8 -*- # @Time : 2019/11/11 15:52 # @Author : 我就是任性-Amo # @FileName: 03-stock_info_query.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680 import os# TODO 1.讀取文件 判斷文件是否存在 存在則讀取 判斷文件內容是否為空 if os.path.exists("stock_data.txt"):with open("stock_data.txt", "r") as file:stock_data = file.readlines()# TODO 2.如果讀取的數(shù)據(jù)不為空 則繼續(xù)進行后續(xù)操作while stock_data:query_info = input("股票查詢接口>>:")if query_info.count("<") == 1 or query_info.count(">") == 1:# TODO 2.1 用戶錄入數(shù)據(jù)時錄入符號symbol = ">" if query_info.find("<") == -1 else "<" # 指定用戶錄入時的符號name, num_str1 = query_info.split(symbol) # 按照用戶錄入的符號進行切割 得到要查找的比較類型以及數(shù)字if stock_data[0].strip().find(name) != -1: # 判斷index = stock_data[0].strip().split(",").index(name) # 得到類型在列表出現(xiàn)的位置print(stock_data[0].strip().split(",")) # 展示total_list = []for i in range(1, len(stock_data)):temp_list = stock_data[i].strip().split(",")# 根據(jù)類型在列表中出現(xiàn)的位置查找對應的其對應的數(shù)據(jù)num_str2 = temp_list[index].replace("%", "") if temp_list[index].find("%") != -1 else temp_list[index]# 判斷表達式 符合條件的往總列表中添加if eval(str(float(num_str2) > float(num_str1))) if symbol == ">" else eval(str(float(num_str2) < float(num_str1))):total_list.append(temp_list)for i in total_list:print(i)print(f"找到{len(total_list)}條")else:# TODO 2.2 用戶錄入數(shù)據(jù)時沒有符號的情況name_list = [stock.strip().split(",") for stock in stock_data ifstock.strip().split(",")[2].find(query_info) != -1]# 展示for name in name_list:print(name)print(f"找到{len(name_list)}條")程序運行結果如下:
28.員工信息管理
# -*- coding: utf-8 -*- # @Time : 2019/11/16 00:17 # @Author : 我就是任性-Amo # @FileName: 04-staffsystem.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680 import os import refilename = "staff_table.txt" # 定義保存員工信息的文件名 condition_list = ["staff_id", "name", "age", "phone", "dept", "enroll_date"]def menu():# 輸出菜單print('''╔———————員工信息管理系統(tǒng)————————╗│ ││ =============== 功能菜單 =============== ││ ││ 1 添加員工信息 ││ 2 刪除員工信息 ││ 3 修改員工信息 ││ 4 查找員工信息 ││ 0 退出系統(tǒng) ││ ========================================== ││ 說明:通過數(shù)字或↑↓方向鍵選擇菜單 │╚———————————————————————╝''')def main():flag = True # 控制是否退出系統(tǒng)while flag:menu() # 顯示菜單option = input("請選擇>>:") # 用戶選擇功能# regexp.sub(): 將字符串中的數(shù)字提取出來 如果用戶輸入中含有非數(shù)字 則替換成''option_str = re.sub('\D', '', option) # 提取數(shù)字if option_str in ['0', '1', '2', '3', '4']:option_int = int(option_str)if option_int == 0:flag = Falseprint("您已退出員工信息管理系統(tǒng)!!!")elif option_int == 1:add() # 添加員工信息elif option_int == 2:delete() # 刪除員工信息elif option_int == 3:update() # 修改員工信息elif option_int == 4:search() # 查找員工信息# passdef search():flag = Truewhile flag:operator_list = [">", "=", "like"] # 定義三種操作符input_info = input(">>>:") # 用戶輸入operator = [operator for operator in operator_list if operator in input_info][0] # 獲取用戶輸入的操作符d_index = input_info.index("d") # 查找到第一個d的位置from_index = input_info.index("from") # 查找到from的位置where_index = input_info.index("where") # 查找到where的位置operator_index = input_info.index(operator) # 查找到對應的操作符位置find_info = input_info[d_index + 2:from_index - 1] # 查找的信息 是所有的員工信息 還是員工信息中具體的某一個condition_type = input_info[where_index + 6:operator_index - 1] # 查找條件condition_value = input_info[operator_index + len(operator) + 1:] # 查找條件的值if condition_value.find("\"") != -1:condition_value = condition_value.replace("\"", "")if os.path.exists(filename):with open(filename, "r") as file:staff_list = file.readlines()if staff_list:index = condition_list.index(condition_type)# 不同的操作符進行不同的判斷if operator == ">":input_age = int(condition_value)for staff in staff_list:if int(staff.split(",")[index]) > input_age:show(staff, find_info)elif operator == "=":for staff in staff_list:if staff.split(",")[index] == condition_value:show(staff, find_info)elif operator == "like":for staff in staff_list:if staff.split(",")[index].startswith(condition_value):show(staff, find_info)query_info = input("是否繼續(xù)查找(y/n):")if query_info == "y":flag = Trueelif query_info == "n":flag = Falsedef add():"""根據(jù)用戶輸入的信息,添加進入到文本文件中:return:"""staff_id = 1 # 員工編號staff_list = []tel_num = [] # 用來存儲文件中所有的電話號碼tel_num_input = [] # 判斷此次用戶輸入的電話號碼是否有重復flag = Trueif os.path.exists(filename):with open(filename, "r") as file:content = file.readlines()if len(content) > 1:staff_id = int(content[-1].strip().split(",")[0]) + 1for staff in content[1:]:tel_num.append(staff.split(",")[3])while flag:staff_id_str = str(staff_id) + ","staff_info = input(">>>:").strip()staff_info = staff_info[staff_info.index("e") + 2:]tel_phone = staff_info.split(",")[2]# 判斷輸入的電話號碼是否在文件中存在或者是在之前已經輸入存儲過if tel_phone in tel_num_input or tel_phone in tel_num:print("你輸入的電話號碼重復...")continuetel_num_input.append(tel_phone)write_info = "\n" + staff_id_str + staff_infostaff_list.append(write_info)tips = input("是否繼續(xù)添加(y/n):")if tips == "y":flag = Truestaff_id += 1elif tips == "n":flag = Falsesave(staff_list)print("員工信息添加成功!!!")def save(staff_list):# 1.打開文件file = open(filename, "a")# 2.寫入for staff in staff_list:file.write(staff)# 3.關閉文件file.close()def delete():"""根據(jù)用戶輸入id刪除文件中對應的用戶信息:return:"""flag = True # 控制是否結束循環(huán)if os.path.exists(filename): # 判斷文件是否存在with open(filename, "r") as file:staff_list = file.readlines()while flag:search_str = input(">>>:").strip()# 查找idstaff_id = search_str[search_str.index("=") + 2:]for staff in staff_list:temp = staff.strip().split(",")[0]# 如果用戶輸入id與文件中讀取到的id相同 則從大列表中進行移除if staff_id == temp:staff_list.remove(staff)else:pass# 判斷是否繼續(xù)刪除tips = input("是否繼續(xù)刪除(y/n):")if tips == "y":flag = Trueelif tips == "n":flag = False# 向文件寫入內容的時候 將最后一個元素的換行去除staff_list[-1] = staff_list[-1].strip()with open(filename, "w") as file:file.writelines(staff_list)print("刪除成功!!!")def update():"""更新員工信息函數(shù)"""flag = True # 控制是否退出更新while flag:input_info = input(">>>:") # 用戶輸入# 例子: update staff_table set dept="Market" where dept = "IT"set_index = input_info.index("set")den_index = input_info.index("=") # 獲取set和第一個=號的索引where_index = input_info.index("where")rden_index = input_info.rindex("=") # 獲取where和最后一個=的位置update_type = input_info[set_index + 4: den_index] # 定位修改員工的哪個具體信息update_value = input_info[den_index + 1:where_index - 1] # 定位修改員工的值condition_type = input_info[where_index + 6:rden_index - 1] # 定位根據(jù)哪個員工的信息去判斷condition_value = input_info[rden_index + 2:] # 符合條件的值if "\"" in update_type: # 去掉引號 否則會匹配不成功update_type = update_type.replace("\"", "")if "\"" in update_value:update_value = update_value.replace("\"", "")if "\"" in condition_type:condition_type = condition_type.replace("\"", "")if "\"" in condition_value:condition_value = condition_value.replace("\"", "")# 讀取文件if os.path.exists(filename):with open(filename, "r") as file:staff_list = file.readlines()new_staff_list = []# 判斷文件內容是否為空if staff_list:# 根據(jù)類型去condition_list查找對應的所以 在根據(jù)對應的索引去查找值index1 = condition_list.index(condition_type)index2 = condition_list.index(update_type)for staff in staff_list:staff_info = staff.split(",")# 判斷文件中查找出的值是否和用戶輸入條件值一致if staff_info[index1] == condition_value:staff_info[index2] = update_valuenew_staff = ",".join(staff_info)else:new_staff = staff# 將符合條件的更改后的員工信息存儲到大列表中new_staff_list.append(new_staff)# 寫入文件with open(filename, "w") as wfile:wfile.writelines(new_staff_list)print("修改成功")# 是否繼續(xù)修改choice = input("是否繼續(xù)修改(y/n):")if choice == "y":flag = Trueelif choice == "n":flag = Falsedef show(staff, find_info, con_list=condition_list):"""員工信息顯示函數(shù):param staff: 員工:param find_info: 顯示所有員工信息 或者是 顯示員工某個具體信息:param con_list: condition_list:return: None"""if find_info == "*":staff_info = staff.split(",")print("staff_id " + staff_info[0] + " name " + staff_info[1] + " age " + staff_info[2] + " phone " + staff_info[3] + " dept " + staff_info[4] + " enroll_date " +staff_info[5].strip())else:staff_info = staff.split(",")find_info_list = find_info.split(",")for info in find_info_list:print(" " + info + " " + staff_info[con_list.index(info)], end="")print()if __name__ == '__main__':main()程序運行結果如下:
29.網絡訪問日志
# -*- coding: utf-8 -*- # @Time : 2019/11/23 00:58 # @Author : 我就是任性-Amo # @FileName: network.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680 import re import osfile_name = "網站訪問日志.txt"def read_txt(filename):"""讀取文件中的數(shù)據(jù):param filename: 文件名:return: 返回文件數(shù)據(jù)列表"""if os.path.exists(filename):with open(filename, "r") as file:log_list = file.readlines()if log_list:return log_listdef total(filename, name):"""統(tǒng)計文件中所有的pv數(shù),uv數(shù),設備列表等:param filename: 需要處理的文本:param name: 傳入需要返回哪個數(shù)據(jù)列表:return: 根據(jù)name 返回對應的列表"""uv_list = [] # 統(tǒng)計所有的uv數(shù)量pv_list = [] # 統(tǒng)計所有的pv數(shù)量equipment_list = [] # 統(tǒng)計所有的設備來源log_list = read_txt(filename) # 讀取文本中的數(shù)據(jù)for log in log_list:# 1.統(tǒng)計本日志文件的總uvre_obj1 = re.match(r"(\d{1,3}\.){3}\d{1,3}", log.strip())if re_obj1:uv_list.append(re_obj1.group())# 2.將符合的pv追加到列表中pv_list.append(log.split("\"")[1])# 3.將符合的設備來源添加到列表中mozilla_index = log.find("Mozilla/5.0")r_index = log.find(")", mozilla_index)if mozilla_index != -1 and r_index != -1:equipment_list.append(log[mozilla_index: r_index + 1])if name == "uv":return uv_listelif name == "pv":return pv_listelif name == "equipment":return equipment_listdef every_hour(filename):"""列出全天每小時的pv、uv數(shù):param filename: 文件名:return: 無"""temp_hour = "00"count = 0log_list = read_txt(filename)every_hour_uv = []for log in log_list:hour = re.search(r"\[.*\]", log).group().split(":")[1]value = ""if re.match(r"(\d{1,3}\.){3}\d{1,3}", log.strip()):value = re.match(r"(\d{1,3}\.){3}\d{1,3}", log.strip()).group()if temp_hour == hour:if value not in every_hour_uv:every_hour_uv.append(value)count += 1if temp_hour == "23" and log == log_list[-1]:print(f"全天{temp_hour}~第二天00時間段的uv數(shù)量為:{len(every_hour_uv) - 1}", end=" ")print(f"pv數(shù)量為:{count}")else:# 因為文件中每一行的數(shù)據(jù)有些并不是以ip開頭 所以就會存在為空# 那么第一次為空的時候在列表中是不存在的 所以要減去為空白的一次temp = temp_hourtemp_hour = hourprint(f"全天{temp}~{temp_hour}時間段的uv數(shù)量為:{len(every_hour_uv) - 1}", end=" ")print(f"pv數(shù)量為:{count}")count = 1every_hour_uv.clear()every_hour_uv.append(value)def show(filename, name, default=1):"""根據(jù)傳入的名稱 統(tǒng)計指定的值以及其對應的數(shù)量 并選擇是否排序及個數(shù):param default: 結果默認降序排列 并且取出前10個數(shù)據(jù):param filename: 文件名:param name: 統(tǒng)計的名稱:return: 返回字典 key:為要查詢的名稱 value:為其對應的數(shù)量"""name1_list = total(filename, name)# 對數(shù)據(jù)進行去重name1_set = set(name1_list)# 定義字典用于返回結果name1_dict = {}if name == "uv":for name1 in name1_set:if name1 not in name1_dict:name1_dict[name1] = name1_list.count(name1)elif name == "pv":for pv in name1_set:try:new_pv = pv.split(" ")[1]if new_pv not in name1_dict:name1_dict[new_pv] = name1_list.count(pv)except IndexError as e:passelif name == "equipment":for equipment in name1_set:if equipment not in name1_dict:name1_dict[equipment] = name1_list.count(equipment)top10_name = sorted(name1_dict.items(), key=lambda item: item[1], reverse=True)[:10]return top10_nameif __name__ == "__main__":print(total(file_name, "uv")) # 測試統(tǒng)計uv數(shù)量every_hour(file_name) # 測試統(tǒng)計一天每小時的uv pv數(shù)量print(show(file_name,?"pv"))??#?測試top10?pv數(shù)量程序運行結果如下:
30.selenium基本操作流程
# -*- coding: utf-8 -*- # @Time : 2019/12/16 00:53 # @Author : 我就是任性-Amo # @FileName: 25.selenium基本操作流程.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680from selenium import webdriver import time# 這里以拉勾網為例子 # 1.準備url和創(chuàng)建瀏覽器對象 url = "https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=" driver = webdriver.Chrome() # 2.發(fā)送請求 driver.get(url) # 3.根據(jù)實際需求判斷是否需要操作滾動條 for j in range(3):driver.execute_script("window.scrollBy(0,1000);")time.sleep(3) # 4.解析數(shù)據(jù) li_list = driver.find_elements_by_xpath("//ul[@class='item_con_list']//li") data_list = [] for li in li_list:# 職位以及地區(qū)position = li.find_element_by_xpath(".//h3").textaddress = li.find_element_by_xpath(".//em").text# 公司名稱company_name = li.find_element_by_xpath(".//div[@class='company_name']/a").text# 薪資范圍 經驗及學歷要求li_b_l = li.find_element_by_xpath(".//div[@class='p_bot']//div[@class='li_b_l']").text.strip()# 工作內容span_list = li.find_elements_by_xpath("//div[@class='li_b_l']//span[@class='']")work = ""for k in span_list:work += k.text# 公司規(guī)模industry = li.find_element_by_xpath(".//div[@class='industry']").text# 公司介紹(福利 團隊等等)introduce = li.find_element_by_xpath(".//div[@class='li_b_r']").text# 5.保存數(shù)據(jù) 這里為了演示將數(shù)據(jù)保存到字典中即可print({"職位": position, "地區(qū)": address, "薪資": li_b_l, "工作內容": work, "公司規(guī)模": industry, "公司介紹": introduce}) # 6.翻頁 找到下一頁的按鈕即可 # 7.退出瀏覽器 driver.quit()程序運行結果如下:
31.字典的排序
# -*- coding: utf-8 -*- # @Time : 2019/12/16 10:05 # @Author : 我就是任性-Amo # @FileName: 26.字典的排序.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680 """ sorted函數(shù):sorted(iterable, key, reverse), sorted一共有iterable,key,reverse這三個參數(shù)1.iterable:表示可迭代對象2.key:一個函數(shù),用來選取參與比較的元素3.reverse:用來指定排序是倒序還是順序reverse=True則是倒序(從大到小),reverse=False則是順序(從小到大),默認是reverse=False """ import operator# 1.字典按照key排序 my_dict = {'lilee': 25, 'age': 24, 'phone': 12} print(sorted(my_dict.keys())) # my_dict.items()返回了三個元素 每個元素都是一個元組 元組中有兩個元素 # 第一個元素為key, 第二個元素為value reverse=True降序排列 print(sorted(my_dict.items(), key=lambda item: item[0], reverse=True))# 2.字典的value值進行排序# 2.1 key()使用lambda匿名函數(shù)取出value值進行排序 print(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))# 2.2 使用operator的itemgetter進行排序() print(sorted(my_dict.items(),?key=operator.itemgetter(1)))程序運行結果如下:
32.字符串切片練習
# -*- coding: utf-8 -*- # @Time : 2019/12/16 15:20 # @Author : 我就是任性-Amo # @FileName: 27.字符串切片練習.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 定義一個字符串 name = "abcdefg" 使用切片得到以下數(shù)據(jù) # 切片的語法: [start_index: end_index: step] # start_index: 表示起始索引 # end_index: 表示結束索引 # step: 表示步長,步長不能為0,且默認值為1 # 列表元組等也是支持切片的 name = "abcdefg"# cde print(name[2:5]) # abcde print(name[:5]) # 省略start_index,保留end_index,這樣會從第一個元素開始,切到end_index - 1的元素為止 # bcdefg print(name[1:]) # 保留start_index,但省略end_index,這樣會從起始索引開始,切到最后一個元素為止 # abcdefg print(name[:]) # 省略start_index、end_index和step,這樣就表示就表示切片整個序列,也就是復制出了一個新的字符串序列 # aceg print(name[::2]) # 省略start_index、end_index,但保留step,表示對整個序列,按照步長的規(guī)則取值 # abcdef print(name[:-1]) # def print(name[3:6]) # gfedcba print(name[::-1]) # 步長為-1表示逆序 #?注意:步長和切片的方向要一致?否則切片失敗程序運行結果如下:
33.字符串方法練習
# -*- coding: utf-8 -*- # @Time : 2019/12/16 16:05 # @Author : 我就是任性-Amo # @FileName: 28.字符串方法的練習.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680name = " gouguoQ " # 移除name變量對應值的兩邊的空格,并輸出移除后的內容 print(name.strip()) # 判斷name變量對應的值是否以"go"開頭,并輸出結果 print(name.startswith("go")) # False # 判斷name變量對應的值是否以"Q"結尾,并輸出結果 print(name.endswith("Q")) # 將name變量對應的值中的"o",替換為"p",并輸出結果 print(name.replace("o", "p")) # 將name變量對應的值根據(jù)"o"分割,并輸出結果 print(name.split("o")) # 請問上一題分割之后得到的值是什么類型(可選) # 上一題分割之后得到的值是列表數(shù)據(jù)類型 # 將name變量對應的值變大寫,并輸出結果 print(name.upper()) # 將name變量對應的值變成小寫,并輸出結果 print(name.lower()) # 請輸出name變量對應的值的第二個字符?請輸出name變量對應的值的前三個字符.請輸出name變量對應值的后2個字符 # 切片 print(name[2:3]) print(name[0:3]) print(name[-2:]) # 請輸出name變量中的值"Q的索引的位置 print(name.index("Q")) # 獲取子序列,僅不包含最后一個字符,如:woaini則獲取woain root則獲取roo temp_str = "woaini" print(temp_str[:-1]) # 利用下劃線將列表的每一個元素拼接成字符串 li = ['gou', 'guo', 'qi'] li = ['gou', 'guo', 'qi'] print("_".join(li))程序運行結果如下:
34.將列表中的數(shù)字類型轉換為字符串類型
# -*- coding: utf-8 -*- # @Time : 2019/12/16 16:33 # @Author : 我就是任性-Amo # @FileName: 29.將列表中的數(shù)字類型轉換為字符串類型.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 代碼題2: 把[1,2,3,4]轉換成"1234"num_list = [1, 2, 3, 4] temp_str = "".join(map(str, num_list)) print(temp_str)程序運行結果如下:
35.把一個元素全為數(shù)字的列表中的所有偶數(shù)加1
# -*- coding: utf-8 -*- # @Time : 2019/12/16 16:44 # @Author : 我就是任性-Amo # @FileName: 30.把一個元素全為數(shù)字的列表中的所有偶數(shù)加1.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 代碼題1: 編程實現(xiàn) 把一個元素全為數(shù)字的列表中的所有偶數(shù)加1 # 思路1: 使用循環(huán) num_list1 = [1, 2, 3, 4, 5, 6, 7, 8] for i in range(len(num_list1)):# 判斷列表中的每一個元素是否能被2整除if num_list1[i] % 2 == 0:# 符合該條件的元素+1num_list1[i] += 1print(num_list1)# 思路2: 使用高階函數(shù) num_list2 = [100, 101, 102, 103, 104, 105, 106, 107] new_list = list(map(lambda x: x + 1 if x % 2 == 0 else x, num_list2)) print(new_list)程序運行結果如下:
36.統(tǒng)計元組中元素出現(xiàn)的個數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/16 18:31 # @Author : 我就是任性-Amo # @FileName: 31.統(tǒng)計元組中元素出現(xiàn)的個數(shù).py # @Software: PyCharm # @Blog : https://blog.csdn.net/xw1680# 代碼題:test = ("a", "b", "c", "a", "c"), # 統(tǒng)計元組中每個元素出現(xiàn)的次數(shù)把最終的結果保存到列表中,例如[('a',2),('b',1),('c',2)]。# 1.使用循環(huán) test = ("a", "b", "c", "a", "c") temp = [] # 定義一個空列表用于去重 如果使用集合不能保證順序 for i in test:if i not in temp:temp.append(i)# 統(tǒng)計temp列表中每個元素在test中出現(xiàn)的次數(shù) 并追加到新列表中 # 使用列表推導式 result = [(i, test.count(i)) for i in temp] print(result)??#?最后的結果與預期的一致程序運行結果如下:
37.循環(huán)練習
# -*- coding: utf-8 -*- # @Time : 2019/12/16 18:49 # @Author : 我就是任性-Amo # @FileName: 32.循環(huán)練習.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 1.使用 while 循環(huán)實現(xiàn)輸出 1,2,3,4,5,7,8,9,11,12 # 分析:使用while打印1-12 但是跳過了6和10 說明要使用continue # 使用while的步驟: # 1.初始值 2.條件判斷語句 3.循環(huán)體 4.條件控制語句 i = 1 while i <= 12:if i == 6 or i == 10:i += 1continueif i == 12:print(i, end="")else:print(i, end=",")i += 1 print() print("***************************") # 2.使用while 循環(huán)輸出100-50,從大到小,如100,99,98…,到50時再從0循環(huán)輸出到50,然后結束 j = 100 while j >= 50:print(j)if j == 50:k = 0while k <= 50:print(k)k += 1j -= 1 print("***************************") # 或者直接使用第二種方法: count = 100 while count > -2:if count >= 50:print(count)else:print(49 - count)count -= 1 print("***************************") # 3.使用 while 循環(huán)實現(xiàn)輸出 1-100 內的所有奇數(shù) m = 1 while m <= 100:if m % 2 != 0:print(m)m += 1 print("***************************") # 4.使用 while 循環(huán)實現(xiàn)輸出 1-100 內的所有偶數(shù) n = 1 while n <= 100:if n % 2 == 0:print(n)n += 1 print("***************************") # 5.使用while循環(huán)實現(xiàn)輸出2-3+4-5+6…+100 的和 j = 2 get_sum = 0 while j <= 100:if j % 2 != 0:get_sum -= jelse:get_sum += jj += 1print(get_sum)38.打印各種圖形
# -*- coding: utf-8 -*- # @Time : 2019/12/16 23:30 # @Author : 我就是任性-Amo # @FileName: 33.打印各種圖形.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 1.打印矩形 row = int(input("row:")) # 控制行數(shù) clo = int(input("clo:")) # 控制每一列星星的個數(shù) for i in range(row):print("*" * clo)print("------------------------------")# 2.打印空心矩形 for i in range(row):if i == 0 or i == row - 1:print("*" * clo)else:print("*" + " " * (clo - 2) + "*") print("------------------------------")# 3.打印等腰直角三角形 for i in range(1, row + 1):print("*" * i) print("------------------------------")# 4.打印空心等腰直角三角形 for i in range(1, row + 1):if i == 1 or i == row:print("*" * i)else:print("*" + " " * (i - 2) + "*")print("------------------------------")# 5.打印等腰三角形 這里的話自定義有點點問題 以后我空了再說 s = 1 # 定義星星的初始個數(shù) for i in range(row + 1):if i < row / 2:print(" " * ((row - s) // 2) + "*" * s)s += 2print("------------------------------")# 6.打印右三角形 for i in range(1, 10):if i >= 6:print("* " * (10 - i))else:print("*?"?*?i)程序運行結果如下:
39.列表操作
# -*- coding: utf-8 -*- # @Time : 2019/12/17 00:05 # @Author : 我就是任性-Amo # @FileName: 34.列表操作.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 題目: 寫代碼,有如下列表,按照要求實現(xiàn)每一個功能li = ["amo", "jerry", "crystal"] # 1.計算列表長度并輸出 print(len(li)) # 2.列表中追加元素"seven",并輸出添加后的列表 li.append("seven") print(li) # 請在列表的第1個位置插入元素"Tony",并輸出添加后的列表 li.insert(0, "Tony") print(li) # 請修改列表第2個位置的元素為"Kelly",并輸出修改后的列表 li[1] = "Kelly" print(li) # 請刪除列表中的元素"jerry",并輸出修改后的列表 li.remove("jerry") print(li) # 請刪除列表中的第2個元素,并輸出刪除的元素的值和刪除元素后的列表 del_value = li.pop(1) print(del_value) print(li) # 請刪除列表中的第3個元素,并輸出刪除元素后的列表 li.pop(2) print(li)li = ["amo", "jerry", "crystal", "paul", "ben"] print(li) # 1.請刪除列表中的第2至5個元素,并輸出刪除元素后的列表 這個的話很簡單 不進行演示 # 使用列表的切片 # 2.請將列表所有的元素反轉,并輸出反轉后的列表 # 這里的話可以使用切片或者是使用reverse()方法 li.reverse() print(li) li = li[::-1] print(li) print("--------------------------") # 請使用for、len、range輸出列表的索引 for i in range(len(li)):print(i) print("--------------------------") # 請使用enumrate輸出列表元素和序號(序號從100開始) for key, value in enumerate(li, 100):print(key, value) print("--------------------------") # 4.請使用for循環(huán)輸出列表的所有元素 for ele in li:print(ele)程序運行結果如下:
40.文件操作
# -*- coding: utf-8 -*- # @Time : 2019/12/17 00:23 # @Author : 我就是任性-Amo # @FileName: 35.文件操作.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 1.有名為poetry.txt的文件,其內容如下,請刪除第三行 """ 昔人已乘黃鶴去,此地空余黃鶴樓. 黃鶴一去不復返,白云千載空悠悠. 晴川歷歷漢陽樹,芳草萋萋鸚鵡洲. 日暮鄉(xiāng)關何處是?煙波江上使人愁. """ with open("poetry.txt", 'r', encoding="utf8") as file:content = file.readlines()content.pop(2)with open("poetry.txt", "w", encoding="utf8") as file:file.writelines(content)# 2.有名為user_info.txt的文件,其內容格式如下,寫一個程序,刪除id為100003的行 """ pizza,100001 alex,100002 egon,100003 """ # 如果是這個文本文件的需求都是只刪除最后一行的數(shù)據(jù)的話 則直接可以使用pop()方法 with open("user_info.txt", "r", encoding="utf8") as file:content = file.readlines()for ele in content:if ele.split(",")[1] == "100003":content.remove(ele) with open("user_info.txt", "w", encoding="utf8") as file:file.writelines(content)41.字符串練習
# -*- coding: utf-8 -*- # @Time : 2019/12/17 10:12 # @Author : 我就是任性-Amo # @FileName: 36.字符串練習.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680 import re# 代碼題1:已知字符串 test = "aAsmr3idd4bgs7Dlsf9eAF",將字符串中的數(shù)字取出,生成一個新的字符串 test = "aAsmr3idd4bgs7Dlsf9eAF" new_str = "" # 1.使用循環(huán) 判斷每一個字符是否是數(shù)字 如果是則將其進行拼接 for i in test:if i.isdigit():new_str += i print(new_str)# 2.使用正則表達式 new_str = "".join(re.findall(r"\d", test)) print(new_str)# 代碼題2:現(xiàn)有字符串 msg = "hel@#$lo pyt \nhon ni\t hao%$" , # 去掉所有不是英文字母的字符,打印結果:"清理以后的結果為: hellopythonnihao"msg = "hel@#$lo pyt \nhon ni\t hao%$" new_str = "" # 1.使用循環(huán) 判斷每一個字符是否是字母 如果是則進行拼接 for i in msg:if i.isalpha():new_str += i print(new_str) # 2.使用正則表達式 new_str = "".join(re.findall("[a-zA-Z]", msg)) print(new_str)程序運行結果如下:
42.數(shù)據(jù)序列綜合練習
# -*- coding: utf-8 -*- # @Time : 2019/12/17 10:57 # @Author : 我就是任性-Amo # @FileName: 38.數(shù)據(jù)序列綜合操作.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680""" 第一題:對數(shù)據(jù)進行清洗,去除數(shù)據(jù)中的`空字符串`、`None`、`廣告`,只留下單詞。對留下的單詞統(tǒng)計次數(shù) 數(shù)據(jù)見info.txt """ # 1.打開文件 f = open("info.txt", encoding="gbk") # 2.操作文件 content = f.readlines() # 返回一個列表 total_list = [] # 3.關閉文件 f.close() for i in content:# 1.去除空白行使用strip()方法temp_str = i.strip()# 2.去除Noneif temp_str == "None":passelse:list1 = temp_str.split("-")total_list.extend(list1) set1 = set(total_list) dict1 = {} for i in set1:dict1[i] = total_list.count(i) print(dict1) print("-------------------------------")""" 第二題: url = "http://{}.58.com/zpjianshen/pn{}" start_url = 'http://{}.58.com/zpjianshen/' start_urls = [] citys = ['北京', '金華', '上海', '深圳', '廣州', '廈門', '武漢', '長沙', '石家莊', '南昌', '青島', '杭州', '合肥', '南寧', '貴陽', '蘭州', '鄭州', '哈爾濱'] cityscode = ['bj', 'jh', 'sh', 'sz', 'gz', 'xm', 'wh', 'cs', 'sjz', 'nc', 'qd', 'hz', 'hf', 'nn', 'gy', 'lz', 'zz','hrb'] # 需求:要求將上面的url補充完整 # 格式如下: # [{'北京':['http://bj.58.com/zpjianshen/pn1',...'http://bj.58.com/zpjianshen/pn30']}, {'金華':['http://jh.58.com/zpjianshen/pn1',...,'http://bj.58.com/zpjianshen/pn30']}] """ # 18個演員 # list1 = [{"趙麗穎": []}, {"林志穎": []}] # 1.定義一個總列表存儲所有的字典 total_lit = [] citys = ['北京', '金華', '上海', '深圳', '廣州', '廈門', '武漢', '長沙', '石家莊', '南昌', '青島', '杭州', '合肥', '南寧', '貴陽', '蘭州', '鄭州', '哈爾濱'] cityscode = ['bj', 'jh', 'sh', 'sz', 'gz', 'xm', 'wh', 'cs', 'sjz', 'nc', 'qd', 'hz', 'hf', 'nn', 'gy', 'lz', 'zz','hrb'] # 2.遍歷citys拿到每一個城市的名字 for i in range(len(citys)):# 2.1 拿到每一個具體城市的名字city = citys[i]# 2.2 拿到城市所對應的citycodecity_code = cityscode[i]# 2.3 拼接urltemp_url = f'http://{city_code}.58.com/zpjianshen/' + "pn{}"# 2.4 構造url_listurl_list = [temp_url.format(i) for i in range(1, 31)]# 2.5 往大列表中追加字典元素total_lit.append({city: url_list}) for i in total_lit:print(i)程序運行結果如下:
{'五險一金': 9856, '包吃': 8265, '包住': 14125, '飯補': 3646, '加班補助': 3893, '交通補助': 4745, '話補': 3513, '年底雙薪': 7417, '廣告': 531, '提供食宿': 7, '周末雙休': 6380, '房補': 3511, '餐補': 20} ------------------------------- {'北京': ['http://bj.58.com/zpjianshen/pn1', 'http://bj.58.com/zpjianshen/pn2', 'http://bj.58.com/zpjianshen/pn3', 'http://bj.58.com/zpjianshen/pn4', 'http://bj.58.com/zpjianshen/pn5', 'http://bj.58.com/zpjianshen/pn6', 'http://bj.58.com/zpjianshen/pn7', 'http://bj.58.com/zpjianshen/pn8', 'http://bj.58.com/zpjianshen/pn9', 'http://bj.58.com/zpjianshen/pn10', 'http://bj.58.com/zpjianshen/pn11', 'http://bj.58.com/zpjianshen/pn12', 'http://bj.58.com/zpjianshen/pn13', 'http://bj.58.com/zpjianshen/pn14', 'http://bj.58.com/zpjianshen/pn15', 'http://bj.58.com/zpjianshen/pn16', 'http://bj.58.com/zpjianshen/pn17', 'http://bj.58.com/zpjianshen/pn18', 'http://bj.58.com/zpjianshen/pn19', 'http://bj.58.com/zpjianshen/pn20', 'http://bj.58.com/zpjianshen/pn21', 'http://bj.58.com/zpjianshen/pn22', 'http://bj.58.com/zpjianshen/pn23', 'http://bj.58.com/zpjianshen/pn24', 'http://bj.58.com/zpjianshen/pn25', 'http://bj.58.com/zpjianshen/pn26', 'http://bj.58.com/zpjianshen/pn27', 'http://bj.58.com/zpjianshen/pn28', 'http://bj.58.com/zpjianshen/pn29', 'http://bj.58.com/zpjianshen/pn30']} {'金華': ['http://jh.58.com/zpjianshen/pn1', 'http://jh.58.com/zpjianshen/pn2', 'http://jh.58.com/zpjianshen/pn3', 'http://jh.58.com/zpjianshen/pn4', 'http://jh.58.com/zpjianshen/pn5', 'http://jh.58.com/zpjianshen/pn6', 'http://jh.58.com/zpjianshen/pn7', 'http://jh.58.com/zpjianshen/pn8', 'http://jh.58.com/zpjianshen/pn9', 'http://jh.58.com/zpjianshen/pn10', 'http://jh.58.com/zpjianshen/pn11', 'http://jh.58.com/zpjianshen/pn12', 'http://jh.58.com/zpjianshen/pn13', 'http://jh.58.com/zpjianshen/pn14', 'http://jh.58.com/zpjianshen/pn15', 'http://jh.58.com/zpjianshen/pn16', 'http://jh.58.com/zpjianshen/pn17', 'http://jh.58.com/zpjianshen/pn18', 'http://jh.58.com/zpjianshen/pn19', 'http://jh.58.com/zpjianshen/pn20', 'http://jh.58.com/zpjianshen/pn21', 'http://jh.58.com/zpjianshen/pn22', 'http://jh.58.com/zpjianshen/pn23', 'http://jh.58.com/zpjianshen/pn24', 'http://jh.58.com/zpjianshen/pn25', 'http://jh.58.com/zpjianshen/pn26', 'http://jh.58.com/zpjianshen/pn27', 'http://jh.58.com/zpjianshen/pn28', 'http://jh.58.com/zpjianshen/pn29', 'http://jh.58.com/zpjianshen/pn30']} {'上海': ['http://sh.58.com/zpjianshen/pn1', 'http://sh.58.com/zpjianshen/pn2', 'http://sh.58.com/zpjianshen/pn3', 'http://sh.58.com/zpjianshen/pn4', 'http://sh.58.com/zpjianshen/pn5', 'http://sh.58.com/zpjianshen/pn6', 'http://sh.58.com/zpjianshen/pn7', 'http://sh.58.com/zpjianshen/pn8', 'http://sh.58.com/zpjianshen/pn9', 'http://sh.58.com/zpjianshen/pn10', 'http://sh.58.com/zpjianshen/pn11', 'http://sh.58.com/zpjianshen/pn12', 'http://sh.58.com/zpjianshen/pn13', 'http://sh.58.com/zpjianshen/pn14', 'http://sh.58.com/zpjianshen/pn15', 'http://sh.58.com/zpjianshen/pn16', 'http://sh.58.com/zpjianshen/pn17', 'http://sh.58.com/zpjianshen/pn18', 'http://sh.58.com/zpjianshen/pn19', 'http://sh.58.com/zpjianshen/pn20', 'http://sh.58.com/zpjianshen/pn21', 'http://sh.58.com/zpjianshen/pn22', 'http://sh.58.com/zpjianshen/pn23', 'http://sh.58.com/zpjianshen/pn24', 'http://sh.58.com/zpjianshen/pn25', 'http://sh.58.com/zpjianshen/pn26', 'http://sh.58.com/zpjianshen/pn27', 'http://sh.58.com/zpjianshen/pn28', 'http://sh.58.com/zpjianshen/pn29', 'http://sh.58.com/zpjianshen/pn30']} {'深圳': ['http://sz.58.com/zpjianshen/pn1', 'http://sz.58.com/zpjianshen/pn2', 'http://sz.58.com/zpjianshen/pn3', 'http://sz.58.com/zpjianshen/pn4', 'http://sz.58.com/zpjianshen/pn5', 'http://sz.58.com/zpjianshen/pn6', 'http://sz.58.com/zpjianshen/pn7', 'http://sz.58.com/zpjianshen/pn8', 'http://sz.58.com/zpjianshen/pn9', 'http://sz.58.com/zpjianshen/pn10', 'http://sz.58.com/zpjianshen/pn11', 'http://sz.58.com/zpjianshen/pn12', 'http://sz.58.com/zpjianshen/pn13', 'http://sz.58.com/zpjianshen/pn14', 'http://sz.58.com/zpjianshen/pn15', 'http://sz.58.com/zpjianshen/pn16', 'http://sz.58.com/zpjianshen/pn17', 'http://sz.58.com/zpjianshen/pn18', 'http://sz.58.com/zpjianshen/pn19', 'http://sz.58.com/zpjianshen/pn20', 'http://sz.58.com/zpjianshen/pn21', 'http://sz.58.com/zpjianshen/pn22', 'http://sz.58.com/zpjianshen/pn23', 'http://sz.58.com/zpjianshen/pn24', 'http://sz.58.com/zpjianshen/pn25', 'http://sz.58.com/zpjianshen/pn26', 'http://sz.58.com/zpjianshen/pn27', 'http://sz.58.com/zpjianshen/pn28', 'http://sz.58.com/zpjianshen/pn29', 'http://sz.58.com/zpjianshen/pn30']} {'廣州': ['http://gz.58.com/zpjianshen/pn1', 'http://gz.58.com/zpjianshen/pn2', 'http://gz.58.com/zpjianshen/pn3', 'http://gz.58.com/zpjianshen/pn4', 'http://gz.58.com/zpjianshen/pn5', 'http://gz.58.com/zpjianshen/pn6', 'http://gz.58.com/zpjianshen/pn7', 'http://gz.58.com/zpjianshen/pn8', 'http://gz.58.com/zpjianshen/pn9', 'http://gz.58.com/zpjianshen/pn10', 'http://gz.58.com/zpjianshen/pn11', 'http://gz.58.com/zpjianshen/pn12', 'http://gz.58.com/zpjianshen/pn13', 'http://gz.58.com/zpjianshen/pn14', 'http://gz.58.com/zpjianshen/pn15', 'http://gz.58.com/zpjianshen/pn16', 'http://gz.58.com/zpjianshen/pn17', 'http://gz.58.com/zpjianshen/pn18', 'http://gz.58.com/zpjianshen/pn19', 'http://gz.58.com/zpjianshen/pn20', 'http://gz.58.com/zpjianshen/pn21', 'http://gz.58.com/zpjianshen/pn22', 'http://gz.58.com/zpjianshen/pn23', 'http://gz.58.com/zpjianshen/pn24', 'http://gz.58.com/zpjianshen/pn25', 'http://gz.58.com/zpjianshen/pn26', 'http://gz.58.com/zpjianshen/pn27', 'http://gz.58.com/zpjianshen/pn28', 'http://gz.58.com/zpjianshen/pn29', 'http://gz.58.com/zpjianshen/pn30']} {'廈門': ['http://xm.58.com/zpjianshen/pn1', 'http://xm.58.com/zpjianshen/pn2', 'http://xm.58.com/zpjianshen/pn3', 'http://xm.58.com/zpjianshen/pn4', 'http://xm.58.com/zpjianshen/pn5', 'http://xm.58.com/zpjianshen/pn6', 'http://xm.58.com/zpjianshen/pn7', 'http://xm.58.com/zpjianshen/pn8', 'http://xm.58.com/zpjianshen/pn9', 'http://xm.58.com/zpjianshen/pn10', 'http://xm.58.com/zpjianshen/pn11', 'http://xm.58.com/zpjianshen/pn12', 'http://xm.58.com/zpjianshen/pn13', 'http://xm.58.com/zpjianshen/pn14', 'http://xm.58.com/zpjianshen/pn15', 'http://xm.58.com/zpjianshen/pn16', 'http://xm.58.com/zpjianshen/pn17', 'http://xm.58.com/zpjianshen/pn18', 'http://xm.58.com/zpjianshen/pn19', 'http://xm.58.com/zpjianshen/pn20', 'http://xm.58.com/zpjianshen/pn21', 'http://xm.58.com/zpjianshen/pn22', 'http://xm.58.com/zpjianshen/pn23', 'http://xm.58.com/zpjianshen/pn24', 'http://xm.58.com/zpjianshen/pn25', 'http://xm.58.com/zpjianshen/pn26', 'http://xm.58.com/zpjianshen/pn27', 'http://xm.58.com/zpjianshen/pn28', 'http://xm.58.com/zpjianshen/pn29', 'http://xm.58.com/zpjianshen/pn30']} {'武漢': ['http://wh.58.com/zpjianshen/pn1', 'http://wh.58.com/zpjianshen/pn2', 'http://wh.58.com/zpjianshen/pn3', 'http://wh.58.com/zpjianshen/pn4', 'http://wh.58.com/zpjianshen/pn5', 'http://wh.58.com/zpjianshen/pn6', 'http://wh.58.com/zpjianshen/pn7', 'http://wh.58.com/zpjianshen/pn8', 'http://wh.58.com/zpjianshen/pn9', 'http://wh.58.com/zpjianshen/pn10', 'http://wh.58.com/zpjianshen/pn11', 'http://wh.58.com/zpjianshen/pn12', 'http://wh.58.com/zpjianshen/pn13', 'http://wh.58.com/zpjianshen/pn14', 'http://wh.58.com/zpjianshen/pn15', 'http://wh.58.com/zpjianshen/pn16', 'http://wh.58.com/zpjianshen/pn17', 'http://wh.58.com/zpjianshen/pn18', 'http://wh.58.com/zpjianshen/pn19', 'http://wh.58.com/zpjianshen/pn20', 'http://wh.58.com/zpjianshen/pn21', 'http://wh.58.com/zpjianshen/pn22', 'http://wh.58.com/zpjianshen/pn23', 'http://wh.58.com/zpjianshen/pn24', 'http://wh.58.com/zpjianshen/pn25', 'http://wh.58.com/zpjianshen/pn26', 'http://wh.58.com/zpjianshen/pn27', 'http://wh.58.com/zpjianshen/pn28', 'http://wh.58.com/zpjianshen/pn29', 'http://wh.58.com/zpjianshen/pn30']} {'長沙': ['http://cs.58.com/zpjianshen/pn1', 'http://cs.58.com/zpjianshen/pn2', 'http://cs.58.com/zpjianshen/pn3', 'http://cs.58.com/zpjianshen/pn4', 'http://cs.58.com/zpjianshen/pn5', 'http://cs.58.com/zpjianshen/pn6', 'http://cs.58.com/zpjianshen/pn7', 'http://cs.58.com/zpjianshen/pn8', 'http://cs.58.com/zpjianshen/pn9', 'http://cs.58.com/zpjianshen/pn10', 'http://cs.58.com/zpjianshen/pn11', 'http://cs.58.com/zpjianshen/pn12', 'http://cs.58.com/zpjianshen/pn13', 'http://cs.58.com/zpjianshen/pn14', 'http://cs.58.com/zpjianshen/pn15', 'http://cs.58.com/zpjianshen/pn16', 'http://cs.58.com/zpjianshen/pn17', 'http://cs.58.com/zpjianshen/pn18', 'http://cs.58.com/zpjianshen/pn19', 'http://cs.58.com/zpjianshen/pn20', 'http://cs.58.com/zpjianshen/pn21', 'http://cs.58.com/zpjianshen/pn22', 'http://cs.58.com/zpjianshen/pn23', 'http://cs.58.com/zpjianshen/pn24', 'http://cs.58.com/zpjianshen/pn25', 'http://cs.58.com/zpjianshen/pn26', 'http://cs.58.com/zpjianshen/pn27', 'http://cs.58.com/zpjianshen/pn28', 'http://cs.58.com/zpjianshen/pn29', 'http://cs.58.com/zpjianshen/pn30']} {'石家莊': ['http://sjz.58.com/zpjianshen/pn1', 'http://sjz.58.com/zpjianshen/pn2', 'http://sjz.58.com/zpjianshen/pn3', 'http://sjz.58.com/zpjianshen/pn4', 'http://sjz.58.com/zpjianshen/pn5', 'http://sjz.58.com/zpjianshen/pn6', 'http://sjz.58.com/zpjianshen/pn7', 'http://sjz.58.com/zpjianshen/pn8', 'http://sjz.58.com/zpjianshen/pn9', 'http://sjz.58.com/zpjianshen/pn10', 'http://sjz.58.com/zpjianshen/pn11', 'http://sjz.58.com/zpjianshen/pn12', 'http://sjz.58.com/zpjianshen/pn13', 'http://sjz.58.com/zpjianshen/pn14', 'http://sjz.58.com/zpjianshen/pn15', 'http://sjz.58.com/zpjianshen/pn16', 'http://sjz.58.com/zpjianshen/pn17', 'http://sjz.58.com/zpjianshen/pn18', 'http://sjz.58.com/zpjianshen/pn19', 'http://sjz.58.com/zpjianshen/pn20', 'http://sjz.58.com/zpjianshen/pn21', 'http://sjz.58.com/zpjianshen/pn22', 'http://sjz.58.com/zpjianshen/pn23', 'http://sjz.58.com/zpjianshen/pn24', 'http://sjz.58.com/zpjianshen/pn25', 'http://sjz.58.com/zpjianshen/pn26', 'http://sjz.58.com/zpjianshen/pn27', 'http://sjz.58.com/zpjianshen/pn28', 'http://sjz.58.com/zpjianshen/pn29', 'http://sjz.58.com/zpjianshen/pn30']} {'南昌': ['http://nc.58.com/zpjianshen/pn1', 'http://nc.58.com/zpjianshen/pn2', 'http://nc.58.com/zpjianshen/pn3', 'http://nc.58.com/zpjianshen/pn4', 'http://nc.58.com/zpjianshen/pn5', 'http://nc.58.com/zpjianshen/pn6', 'http://nc.58.com/zpjianshen/pn7', 'http://nc.58.com/zpjianshen/pn8', 'http://nc.58.com/zpjianshen/pn9', 'http://nc.58.com/zpjianshen/pn10', 'http://nc.58.com/zpjianshen/pn11', 'http://nc.58.com/zpjianshen/pn12', 'http://nc.58.com/zpjianshen/pn13', 'http://nc.58.com/zpjianshen/pn14', 'http://nc.58.com/zpjianshen/pn15', 'http://nc.58.com/zpjianshen/pn16', 'http://nc.58.com/zpjianshen/pn17', 'http://nc.58.com/zpjianshen/pn18', 'http://nc.58.com/zpjianshen/pn19', 'http://nc.58.com/zpjianshen/pn20', 'http://nc.58.com/zpjianshen/pn21', 'http://nc.58.com/zpjianshen/pn22', 'http://nc.58.com/zpjianshen/pn23', 'http://nc.58.com/zpjianshen/pn24', 'http://nc.58.com/zpjianshen/pn25', 'http://nc.58.com/zpjianshen/pn26', 'http://nc.58.com/zpjianshen/pn27', 'http://nc.58.com/zpjianshen/pn28', 'http://nc.58.com/zpjianshen/pn29', 'http://nc.58.com/zpjianshen/pn30']} {'青島': ['http://qd.58.com/zpjianshen/pn1', 'http://qd.58.com/zpjianshen/pn2', 'http://qd.58.com/zpjianshen/pn3', 'http://qd.58.com/zpjianshen/pn4', 'http://qd.58.com/zpjianshen/pn5', 'http://qd.58.com/zpjianshen/pn6', 'http://qd.58.com/zpjianshen/pn7', 'http://qd.58.com/zpjianshen/pn8', 'http://qd.58.com/zpjianshen/pn9', 'http://qd.58.com/zpjianshen/pn10', 'http://qd.58.com/zpjianshen/pn11', 'http://qd.58.com/zpjianshen/pn12', 'http://qd.58.com/zpjianshen/pn13', 'http://qd.58.com/zpjianshen/pn14', 'http://qd.58.com/zpjianshen/pn15', 'http://qd.58.com/zpjianshen/pn16', 'http://qd.58.com/zpjianshen/pn17', 'http://qd.58.com/zpjianshen/pn18', 'http://qd.58.com/zpjianshen/pn19', 'http://qd.58.com/zpjianshen/pn20', 'http://qd.58.com/zpjianshen/pn21', 'http://qd.58.com/zpjianshen/pn22', 'http://qd.58.com/zpjianshen/pn23', 'http://qd.58.com/zpjianshen/pn24', 'http://qd.58.com/zpjianshen/pn25', 'http://qd.58.com/zpjianshen/pn26', 'http://qd.58.com/zpjianshen/pn27', 'http://qd.58.com/zpjianshen/pn28', 'http://qd.58.com/zpjianshen/pn29', 'http://qd.58.com/zpjianshen/pn30']} {'杭州': ['http://hz.58.com/zpjianshen/pn1', 'http://hz.58.com/zpjianshen/pn2', 'http://hz.58.com/zpjianshen/pn3', 'http://hz.58.com/zpjianshen/pn4', 'http://hz.58.com/zpjianshen/pn5', 'http://hz.58.com/zpjianshen/pn6', 'http://hz.58.com/zpjianshen/pn7', 'http://hz.58.com/zpjianshen/pn8', 'http://hz.58.com/zpjianshen/pn9', 'http://hz.58.com/zpjianshen/pn10', 'http://hz.58.com/zpjianshen/pn11', 'http://hz.58.com/zpjianshen/pn12', 'http://hz.58.com/zpjianshen/pn13', 'http://hz.58.com/zpjianshen/pn14', 'http://hz.58.com/zpjianshen/pn15', 'http://hz.58.com/zpjianshen/pn16', 'http://hz.58.com/zpjianshen/pn17', 'http://hz.58.com/zpjianshen/pn18', 'http://hz.58.com/zpjianshen/pn19', 'http://hz.58.com/zpjianshen/pn20', 'http://hz.58.com/zpjianshen/pn21', 'http://hz.58.com/zpjianshen/pn22', 'http://hz.58.com/zpjianshen/pn23', 'http://hz.58.com/zpjianshen/pn24', 'http://hz.58.com/zpjianshen/pn25', 'http://hz.58.com/zpjianshen/pn26', 'http://hz.58.com/zpjianshen/pn27', 'http://hz.58.com/zpjianshen/pn28', 'http://hz.58.com/zpjianshen/pn29', 'http://hz.58.com/zpjianshen/pn30']} {'合肥': ['http://hf.58.com/zpjianshen/pn1', 'http://hf.58.com/zpjianshen/pn2', 'http://hf.58.com/zpjianshen/pn3', 'http://hf.58.com/zpjianshen/pn4', 'http://hf.58.com/zpjianshen/pn5', 'http://hf.58.com/zpjianshen/pn6', 'http://hf.58.com/zpjianshen/pn7', 'http://hf.58.com/zpjianshen/pn8', 'http://hf.58.com/zpjianshen/pn9', 'http://hf.58.com/zpjianshen/pn10', 'http://hf.58.com/zpjianshen/pn11', 'http://hf.58.com/zpjianshen/pn12', 'http://hf.58.com/zpjianshen/pn13', 'http://hf.58.com/zpjianshen/pn14', 'http://hf.58.com/zpjianshen/pn15', 'http://hf.58.com/zpjianshen/pn16', 'http://hf.58.com/zpjianshen/pn17', 'http://hf.58.com/zpjianshen/pn18', 'http://hf.58.com/zpjianshen/pn19', 'http://hf.58.com/zpjianshen/pn20', 'http://hf.58.com/zpjianshen/pn21', 'http://hf.58.com/zpjianshen/pn22', 'http://hf.58.com/zpjianshen/pn23', 'http://hf.58.com/zpjianshen/pn24', 'http://hf.58.com/zpjianshen/pn25', 'http://hf.58.com/zpjianshen/pn26', 'http://hf.58.com/zpjianshen/pn27', 'http://hf.58.com/zpjianshen/pn28', 'http://hf.58.com/zpjianshen/pn29', 'http://hf.58.com/zpjianshen/pn30']} {'南寧': ['http://nn.58.com/zpjianshen/pn1', 'http://nn.58.com/zpjianshen/pn2', 'http://nn.58.com/zpjianshen/pn3', 'http://nn.58.com/zpjianshen/pn4', 'http://nn.58.com/zpjianshen/pn5', 'http://nn.58.com/zpjianshen/pn6', 'http://nn.58.com/zpjianshen/pn7', 'http://nn.58.com/zpjianshen/pn8', 'http://nn.58.com/zpjianshen/pn9', 'http://nn.58.com/zpjianshen/pn10', 'http://nn.58.com/zpjianshen/pn11', 'http://nn.58.com/zpjianshen/pn12', 'http://nn.58.com/zpjianshen/pn13', 'http://nn.58.com/zpjianshen/pn14', 'http://nn.58.com/zpjianshen/pn15', 'http://nn.58.com/zpjianshen/pn16', 'http://nn.58.com/zpjianshen/pn17', 'http://nn.58.com/zpjianshen/pn18', 'http://nn.58.com/zpjianshen/pn19', 'http://nn.58.com/zpjianshen/pn20', 'http://nn.58.com/zpjianshen/pn21', 'http://nn.58.com/zpjianshen/pn22', 'http://nn.58.com/zpjianshen/pn23', 'http://nn.58.com/zpjianshen/pn24', 'http://nn.58.com/zpjianshen/pn25', 'http://nn.58.com/zpjianshen/pn26', 'http://nn.58.com/zpjianshen/pn27', 'http://nn.58.com/zpjianshen/pn28', 'http://nn.58.com/zpjianshen/pn29', 'http://nn.58.com/zpjianshen/pn30']} {'貴陽': ['http://gy.58.com/zpjianshen/pn1', 'http://gy.58.com/zpjianshen/pn2', 'http://gy.58.com/zpjianshen/pn3', 'http://gy.58.com/zpjianshen/pn4', 'http://gy.58.com/zpjianshen/pn5', 'http://gy.58.com/zpjianshen/pn6', 'http://gy.58.com/zpjianshen/pn7', 'http://gy.58.com/zpjianshen/pn8', 'http://gy.58.com/zpjianshen/pn9', 'http://gy.58.com/zpjianshen/pn10', 'http://gy.58.com/zpjianshen/pn11', 'http://gy.58.com/zpjianshen/pn12', 'http://gy.58.com/zpjianshen/pn13', 'http://gy.58.com/zpjianshen/pn14', 'http://gy.58.com/zpjianshen/pn15', 'http://gy.58.com/zpjianshen/pn16', 'http://gy.58.com/zpjianshen/pn17', 'http://gy.58.com/zpjianshen/pn18', 'http://gy.58.com/zpjianshen/pn19', 'http://gy.58.com/zpjianshen/pn20', 'http://gy.58.com/zpjianshen/pn21', 'http://gy.58.com/zpjianshen/pn22', 'http://gy.58.com/zpjianshen/pn23', 'http://gy.58.com/zpjianshen/pn24', 'http://gy.58.com/zpjianshen/pn25', 'http://gy.58.com/zpjianshen/pn26', 'http://gy.58.com/zpjianshen/pn27', 'http://gy.58.com/zpjianshen/pn28', 'http://gy.58.com/zpjianshen/pn29', 'http://gy.58.com/zpjianshen/pn30']} {'蘭州': ['http://lz.58.com/zpjianshen/pn1', 'http://lz.58.com/zpjianshen/pn2', 'http://lz.58.com/zpjianshen/pn3', 'http://lz.58.com/zpjianshen/pn4', 'http://lz.58.com/zpjianshen/pn5', 'http://lz.58.com/zpjianshen/pn6', 'http://lz.58.com/zpjianshen/pn7', 'http://lz.58.com/zpjianshen/pn8', 'http://lz.58.com/zpjianshen/pn9', 'http://lz.58.com/zpjianshen/pn10', 'http://lz.58.com/zpjianshen/pn11', 'http://lz.58.com/zpjianshen/pn12', 'http://lz.58.com/zpjianshen/pn13', 'http://lz.58.com/zpjianshen/pn14', 'http://lz.58.com/zpjianshen/pn15', 'http://lz.58.com/zpjianshen/pn16', 'http://lz.58.com/zpjianshen/pn17', 'http://lz.58.com/zpjianshen/pn18', 'http://lz.58.com/zpjianshen/pn19', 'http://lz.58.com/zpjianshen/pn20', 'http://lz.58.com/zpjianshen/pn21', 'http://lz.58.com/zpjianshen/pn22', 'http://lz.58.com/zpjianshen/pn23', 'http://lz.58.com/zpjianshen/pn24', 'http://lz.58.com/zpjianshen/pn25', 'http://lz.58.com/zpjianshen/pn26', 'http://lz.58.com/zpjianshen/pn27', 'http://lz.58.com/zpjianshen/pn28', 'http://lz.58.com/zpjianshen/pn29', 'http://lz.58.com/zpjianshen/pn30']} {'鄭州': ['http://zz.58.com/zpjianshen/pn1', 'http://zz.58.com/zpjianshen/pn2', 'http://zz.58.com/zpjianshen/pn3', 'http://zz.58.com/zpjianshen/pn4', 'http://zz.58.com/zpjianshen/pn5', 'http://zz.58.com/zpjianshen/pn6', 'http://zz.58.com/zpjianshen/pn7', 'http://zz.58.com/zpjianshen/pn8', 'http://zz.58.com/zpjianshen/pn9', 'http://zz.58.com/zpjianshen/pn10', 'http://zz.58.com/zpjianshen/pn11', 'http://zz.58.com/zpjianshen/pn12', 'http://zz.58.com/zpjianshen/pn13', 'http://zz.58.com/zpjianshen/pn14', 'http://zz.58.com/zpjianshen/pn15', 'http://zz.58.com/zpjianshen/pn16', 'http://zz.58.com/zpjianshen/pn17', 'http://zz.58.com/zpjianshen/pn18', 'http://zz.58.com/zpjianshen/pn19', 'http://zz.58.com/zpjianshen/pn20', 'http://zz.58.com/zpjianshen/pn21', 'http://zz.58.com/zpjianshen/pn22', 'http://zz.58.com/zpjianshen/pn23', 'http://zz.58.com/zpjianshen/pn24', 'http://zz.58.com/zpjianshen/pn25', 'http://zz.58.com/zpjianshen/pn26', 'http://zz.58.com/zpjianshen/pn27', 'http://zz.58.com/zpjianshen/pn28', 'http://zz.58.com/zpjianshen/pn29', 'http://zz.58.com/zpjianshen/pn30']} {'哈爾濱':?['http://hrb.58.com/zpjianshen/pn1',?'http://hrb.58.com/zpjianshen/pn2',?'http://hrb.58.com/zpjianshen/pn3',?'http://hrb.58.com/zpjianshen/pn4',?'http://hrb.58.com/zpjianshen/pn5',?'http://hrb.58.com/zpjianshen/pn6',?'http://hrb.58.com/zpjianshen/pn7',?'http://hrb.58.com/zpjianshen/pn8',?'http://hrb.58.com/zpjianshen/pn9',?'http://hrb.58.com/zpjianshen/pn10',?'http://hrb.58.com/zpjianshen/pn11',?'http://hrb.58.com/zpjianshen/pn12',?'http://hrb.58.com/zpjianshen/pn13',?'http://hrb.58.com/zpjianshen/pn14',?'http://hrb.58.com/zpjianshen/pn15',?'http://hrb.58.com/zpjianshen/pn16',?'http://hrb.58.com/zpjianshen/pn17',?'http://hrb.58.com/zpjianshen/pn18',?'http://hrb.58.com/zpjianshen/pn19',?'http://hrb.58.com/zpjianshen/pn20',?'http://hrb.58.com/zpjianshen/pn21',?'http://hrb.58.com/zpjianshen/pn22',?'http://hrb.58.com/zpjianshen/pn23',?'http://hrb.58.com/zpjianshen/pn24',?'http://hrb.58.com/zpjianshen/pn25',?'http://hrb.58.com/zpjianshen/pn26',?'http://hrb.58.com/zpjianshen/pn27',?'http://hrb.58.com/zpjianshen/pn28',?'http://hrb.58.com/zpjianshen/pn29',?'http://hrb.58.com/zpjianshen/pn30']}43.函數(shù)基礎練習
# -*- coding: utf-8 -*- # @Time : 2019/12/17 10:21 # @Author : 我就是任性-Amo # @FileName: 37.函數(shù)練習.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 1.打印圖形(函數(shù)嵌套) # 1.1 打印一條橫線 # 1.2 打印多條橫線 # 2.這里的話是可以使用裝飾器進行實現(xiàn)的def print_line():"""打印一條橫線"""print("-------------------")def print_lines(num):"""打印多條橫線"""for i in range(num):print_line()print_line() # 調用普通函數(shù) print("*******************") print_lines(4) print("*******************")# 2.函數(shù)計算(函數(shù)嵌套) # 2.1 求三個數(shù)之和 # 2.2 求三個數(shù)平均值 def get_sum(a, b, c):"""求三個數(shù)之和"""return a + b + cdef get_average(a, b, c):return get_sum(a, b, c) / 3print(get_average(10, 20, 30)) print("*******************")# 3.定義函數(shù)findall,要求返回符合要求的所有位置的起始下標,如字符串"helloworldhellopythonhelloc++hellojava", # 需要找出里面所有的"hello"的位置,返回的格式是一個元組,即: (0,10,21,29) temp_str = "helloworldhellopythonhelloc++hellojava"def findall(tem_str, find_str):"""tem_str: 查找的字符串find_str: 查找的單詞"""index = 0index_list = []while True:index = tem_str.find(find_str, index) # 每次index都在變化 變化的長度就是要查找單詞的長度if index == -1:breakindex_list.append(index) # 將所有的下標都追加到列表中index += len(find_str)return tuple(index_list) # 為了和題目一致 將列表轉換為元組print(findall(temp_str, "hello")) # 測試在指定的字符串中查找所有的"hello"的下標 # 4.定義一個函數(shù) sum_test 接收一個參數(shù) n ,在函數(shù)中計算 1 + 2 + 3 + ... + n 的值,并打印結果。print("*******************")def sum_test(n):result = 0for i in range(1, n + 1):result += ireturn resultprint(sum_test(100))運行結果如下:
44.復制文本文件
# -*- coding: utf-8 -*- # @Time : 2019/12/17 11:03 # @Author : 我就是任性-Amo # @FileName: 39.復制文件.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 1.復制普通文本文件 # filename = input(">>>:") filename = "1.兩個變量的交換.py" # 一般的話 我們在windows中復制文件 都會在文件名末尾默認添加-副本 new_filename = filename[:filename.rfind(".")] + " - 副本" + filename[filename.rfind("."):] # 1.打開文件 f1 = open(filename, "r") f2 = open(new_filename, "w") # 2.讀取文件內容 并將讀取的文件寫入另一個新的文件中 content = f1.read() f2.write(content) # 3.關閉文件 f2.close() f1.close()# 2.復制圖片 filename = "陳瑤.jpeg" # 一般的話 我們在windows中復制文件 都會在文件名末尾默認添加-副本 new_filename = filename[:filename.rfind(".")] + " - 副本" + filename[filename.rfind("."):] # 1.打開文件 f3 = open(filename, "rb") f4 = open(new_filename, "wb") # 2.讀取文件內容 并將讀取的文件寫入另一個新的文件中 content = f3.read() f4.write(content) # 3.關閉文件 f4.close() f3.close()程序運行結果如下:
45.函數(shù)參數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/17 17:32 # @Author : 我就是任性-Amo # @FileName: 40.函數(shù)參數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680# 1.函數(shù)傳參的方式 def test(a, b, c):print(a, b, c)# 1.1 位置傳參 test(10, 20, 30) # 1.2 序列傳參數(shù)(也是位置傳參的一種) test(*"ABC") # 使用星號將"ABC"拆解為"A" "B" "C" 然后在按照位置傳參的方式去匹配函數(shù)的形參 # 1.3 關鍵字傳參 test(a=10, c=30, b=20) # 根據(jù)名字傳遞參數(shù) # 1.4 雙星號字典傳參 # 字典的key要和函數(shù)行參的名字一致 test(**{"a": "amo", "b": "paul", "c": "jason"})# 2.函數(shù)定義參數(shù)的方式 # 2.1 位置形參 def test2(a, b, c):pass# 2.2 缺省參數(shù) # 因為大部分人的國籍都是中國,所以此時我們可以指定默認的參數(shù) # 如果用戶有傳入實際的國籍 就以用戶實際傳入的參數(shù)為準 否則默認就為中國 def person_info(name, age, nationality="中國"):print(name, age, nationality)person_info("amo", 18) person_info("奧巴馬", 23, "美國")# 2.3 命名關鍵字形參 # *標識著這個函數(shù)的形參為命名關鍵字形參 沒有其他實際的含義 # 表示著 def test3(*, a, b, c):print(a, b, c) # 命名關鍵字行參只能是使用關鍵字傳參的方式或者是雙星號字典傳參的方式test3(a=10, b=20, c=30) test3(**{"a": 30, "b": 20, "c": 10})# 2.4 星號元組形參 # 用于接受多余的位置參數(shù) 一般使用*args表示 def test4(*args):print(args)test4(10, 20, 30, 40) # 將10,20,30,40先打包成一個元組,然后賦值給args test4(10, 20, *[30, 40, 50])# 2.5 雙星號字典形參 def test5(**kwargs):print(kwargs)test5(a=1, b=2, c=3) # 將所有的變量作為字典的key,值作為字典的value 然后傳遞給變量kwargs test5(**{"name":?"amo",?"age":?18,?"is_male":?True})程序運行結果如下:
46.檢索敏感詞并描紅輸出
# -*- coding: utf-8 -*- # @Time : 2019/12/17 18:51 # @Author : 我就是任性-Amo # @FileName: 41.檢索敏感詞并描紅輸出.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680""" 需求:敏感詞,一般是指帶有暴力傾向、不健康的色彩或過度宣傳營銷的詞或用語,也有一些網站根據(jù)自身實際情況, 設定一些適用于網站的特殊敏感詞。例如在淘寶、京東等平臺中,對于商品宣傳用語有一定的限定,如"盜版" "水貨" "山寨" "領先" "最佳" "最大"和"唯一" 等詞語都不能用于產品宣傳,否則可能造成商品下架及其他處罰。 為了不讓敏感詞對企業(yè)宣傳、營銷帶來損害,可以使用程序檢測敏感詞。廣告法規(guī)定的限制敏感詞很多,可以先建立敏感詞庫,然后對輸入的文字進行敏感詞檢索輸出.本例稍加修改,即可實現(xiàn)如下功能,快來試試吧!輸入運營文字,實現(xiàn)用星號標注敏感詞。查找多個文件中的敏感詞,可以將敏感詞保存到文件中,然后從文件讀取敏感詞進行檢測。替換文本或文件中的指定文字并輸出替換個數(shù)。 """word = input("請輸入或者拷貝含有敏感詞的宣傳文字: \n") sensitive = ["第一", "國家級", "最高級", "最佳", "獨一無二", "一流", "僅此一次", "頂級", "頂尖", "尖端", "極品", "極佳", "絕佳", "絕對", "終極", "極致", "首個","首選", "獨家", "首發(fā)", "首次", "首款", "金牌", "名牌", "王牌", "領袖", "領先", "領導", "締造者", "巨星", "掌門人", "至尊", "巔峰", "奢侈","資深", "之王", "王者", "冠軍"] # 使用列表建立敏感詞庫sensitive_find = [] # 存儲查找到的敏感詞 new_word = word # 復制一份用戶輸入的內容 用來標紅 for item in sensitive:if word.count(item) > 0: # 查找每個敏感詞匯在用戶輸入的內容是否出現(xiàn)sensitive_find.append(item + ":" + str(word.count(item)) + "次") # 記錄敏感詞的出現(xiàn)次數(shù)new_word = new_word.replace(item, "\033[1;31m" + item + "\033[0m") # 對敏感詞描紅輸出print("發(fā)現(xiàn)敏感詞匯如下:") for item in sensitive_find:print(item)print("敏感詞位置已用星號進行標注:?\n"?+?new_word)程序運行結果如下:
47.實現(xiàn)字符串與列表等數(shù)據(jù)去重
# -*- coding: utf-8 -*- # @Time : 2019/12/17 19:20 # @Author : 我就是任性-Amo # @FileName: 42.實現(xiàn)字符串與列表等數(shù)據(jù)的去除.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680""" 背景: 隨著大數(shù)據(jù),云技術等的發(fā)展,各行各業(yè)每天都會產生海量的大數(shù)據(jù),如何讓這些大數(shù)據(jù)逐步為人類創(chuàng)造更多的價值, 為企業(yè)所用,已經成為互聯(lián)網經濟的核心發(fā)展方向。 由于目前各行各業(yè)產生的大數(shù)據(jù)會有很多重復的數(shù)據(jù),影響分析效率, 因此進行大數(shù)據(jù)分析的第一步,是檢測和消除其中的重復數(shù)據(jù),通過數(shù)據(jù)去重,一方面是減少存儲空間和網絡帶寬的占用另一方面可以減少數(shù)據(jù)分析量。 數(shù)據(jù)去重又稱重復數(shù)據(jù)刪除,是指在一個數(shù)據(jù)集合中,找出重復的數(shù)據(jù)并將其刪除,只保存唯一的數(shù)據(jù)單元。 Python主要操作的數(shù)據(jù)有字符串和列表,該如何在Python中對字符串和列表去重呢? """# 字符串去重的5種方法 # 1.通過for循環(huán)遍歷字符串去重 name = "王李張李陳王楊張吳周王劉趙黃吳楊" new_name = '' for char in name:if char not in new_name: # 如果不在新的字符串中new_name += char # 拼接到新字符串中的末尾print(new_name) # 2.通過while循環(huán)遍歷字符串去重 name = "王李張李陳王楊張吳周王劉趙黃吳楊" new_name = '' i = 0 while i <= len(name) - 1:if name[i] not in new_name:new_name += name[i]i += 1 print(new_name) # 3.使用列表的方法去重 name = "王李張李陳王楊張吳周王劉趙黃吳楊" new_name = '' name_set = set(name) # 對字符串進行去重 print("".join(sorted(name_set, key=name.index))) # 按照name字符串下標進行排序 # 4.在原字符串中直接刪除 name = "王李張李陳王楊張吳周王劉趙黃吳楊" length = len(name) # 字符串下標的總長度 for s in name:if name[0] in name[1:length]:name = name[1:length]else:name = name[1:length] + name[0] print(name) # 這個的話沒有按照原來的順序進行排列 感覺不是太好 # 5.使用fromkeys()方法把字符串轉成字典 name = "王李張李陳王楊張吳周王劉趙黃吳楊" zd = {}.fromkeys(name) my_list = list(zd.keys()) print("".join(my_list))# 列表的去重方法 # 定義一個列表:下面的各種方法都將使用該列表作為操作數(shù)據(jù) city = ['上海', "廣州", "上海", "成都", "上海", "上海", "北京", "上海", "廣州", "北京", "上海"] # 方法1: for循環(huán)語句 new_city = [] for item in city:if item not in new_city:new_city.append(item) print(new_city) # 方法2: set()方法 改變原來的順序 print(list(set(city))) # 方法3: set()方法 不改變原來數(shù)據(jù)的順序 city_set = set(city) new_city = sorted(city_set, key=city.index) print(new_city) # 方法4: count()方法統(tǒng)計并刪除,需要先排序(改變原來順序) city.sort() for x in city:while city.count(x) > 1:del city[city.index(x)] print(city)# 方法5: 把列表轉成字典 my_list = list({}.fromkeys(city).keys()) print(my_list)程序運行結果如下:
48.匿名函數(shù)lambda
# -*- coding: utf-8 -*- # @Time : 2019/12/17 20:11 # @Author : 我就是任性-Amo # @FileName: 43.lambda表達式.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680""" lambda表達式運用場景:如果一個函數(shù)有一個返回值,并且只有一句代碼,可以使用lambda簡化 語法:lambda 參數(shù)列表: 表達式 lambda表達式的參數(shù)可有可?,函數(shù)的參數(shù)在lambda表達式中完全適? lambda函數(shù)能接收任何數(shù)量的參數(shù)但只能返回?個表達式的值 """ # 1.lambda表達式實現(xiàn)兩個數(shù)的和 print((lambda x, y: x + y)(100, 200))# 2.lambda的參數(shù)形式 # 2.1 無參數(shù) print((lambda: 100)()) # 2.2 一個參數(shù) print((lambda x: x)("hello amo")) # 2.3 默認參數(shù) print((lambda a, b, c=100: a + b + c)(10, 20)) # 2.4 可變參數(shù) **args print((lambda *args: args)(10, 20, 30)) # 這里的可變參數(shù)傳到lambda之后,返回元組 # 2.5 可變參數(shù) **kwargs print((lambda **kwargs: kwargs)(name='amo', age=18))# 3.lambda表達式的運用: # 3.1 帶判斷的lambda表達式 print((lambda a, b: a if a > b else b)(1000, 500)) # 3.2 列表數(shù)據(jù)按字典key的值排序 students = [{'name': 'TOM', 'age': 20},{'name': 'ROSE', 'age': 19},{'name': 'Jack', 'age': 22}] # 按name值升序排列 students.sort(key=lambda x: x['name']) print(students) # 按name值降序排列 students.sort(key=lambda x: x['name'], reverse=True) print(students) # 按age值升序排列 students.sort(key=lambda x: x['age']) print(students) # 3.3 當做參數(shù)傳入高階函數(shù) num_list = [1, 2, 3, 4, 5, 6, 7] # 對num_list中的每個數(shù)字進行+1 print(list(map(lambda?x:?x?+?1,?num_list)))程序運行結果如下:
49.使用MD5或SHA1等算法對用戶密碼進行加密
# -*- coding: utf-8 -*- # @Time : 2019/12/17 22:42 # @Author : 我就是任性-Amo # @FileName: 44.使用md5或sha1等算法對用戶密碼進行加密.py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680 import hashlib import hmac # 采用哈希算法計算后的MD5加密""" 問題背景:互聯(lián)網.上每天都有億量級別的數(shù)據(jù)在進行交互,與此同時,我們每天也都會看到 各種各樣類似"用戶信息泄露""**公司用戶密碼慘遭破解"的類似新聞。 網絡安全在當今的互聯(lián)網時代越來越重要,而密碼安全就是其中最基礎的一種保護用戶信息的方式, 比如我們登錄淘寶、京東,或者自己開發(fā)一些項目的時候,通常都會將用戶密碼加密之后,再進行存儲. """# 1.解決方案: # 使用Python對用戶密碼進行加密非常簡單,因為Python中提供了一個hashlib模塊,該模塊中提供了常用的加密算法,如MD5、SHA1等等, # 例如要對輸入的密碼進行MD5加密,可以使用如下代碼:content = input("請輸入要加密的內容:") # MD5加密(返回32位十六進制字符串) md5 = hashlib.md5() md5.update(content.encode("utf8")) print("MD5加密:" + md5.hexdigest()) # MD5是最常見的加密算法,速度很快,生成結果是固定的128位字節(jié),通常用一個32位的十六進制字符串表示。# 使用SHA1加密用戶密碼的方式與MD5類似,代碼如下: content = input("請輸入要加密的內容:") # SHA1加密(返回40位十六進制表示字符串) sha1 = hashlib.sha1() sha1.update(content.encode("utf8")) print("SHA1加密:" + sha1.hexdigest())# 另外,hashlib模塊中還提供了比SHA1更安全的算法,比如SHA256、SHA512等, # 但是越安全的算法不僅越慢,而且返回結果的長度更長。例如,使用SHA256對用戶輸入的密碼進行加密,代碼如下: content = input("請輸入要加密的內容:") # SHA256加密(返回64位十六進制表示字符串) sha256 = hashlib.sha256() sha256.update(content.encode("utf8")) print("SHA256加密:" + sha256.hexdigest())# 上面介紹了幾種普通的加密算法,但對于黑客來說,他們很容易利用常用口令的MD5或SHA1.值 # 反推出用戶的明文密碼。因此,為了確保存儲的密碼不是那些已經被計算出來的固定值, # 我們可以為.原始密碼加一個隨機的字符串(key)來實現(xiàn)這個功能,Python中的hmac模塊提供了一種Hmac算法, # 它可以在計算哈希碼的過程中,把key值混入計算過程中,這種加密方式更安全,其實現(xiàn)代碼如下: content = input("請輸入要加密的內容:") pwd = content.encode("utf8") key = 'id'.encode("utf8") h = hmac.new(key, pwd, digestmod="MD5") print("更安全的MD5加密:"?+?h.hexdigest())程序運行結果如下:
50.高階函數(shù)
# -*- coding: utf-8 -*- # @Time : 2019/12/17 23:57 # @Author : 我就是任性-Amo # @FileName: 45.高階函數(shù).py # @Software: PyCharm # @Blog :https://blog.csdn.net/xw1680 from functools import reduce""" 高階函數(shù): 高階函數(shù)英文叫Higher-order function 編寫高階函數(shù),就是讓函數(shù)的參數(shù)能夠接收別的函數(shù)。 把函數(shù)作為參數(shù)傳入,這樣的函數(shù)稱為高階函數(shù),函數(shù)式編程就是指這種高度抽象的編程范式。 """""" 我們先看map。map()函數(shù)接收兩個參數(shù),一個是函數(shù),一個是Iterable,map將傳入的函數(shù)依次作用到序列的每個元素,并把結果作為新的Iterator返回。 舉例說明,比如我們有一個函數(shù)f(x)=x2,要把這個函數(shù)作用在一個list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()實現(xiàn)如下: """ num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(list(map(lambda x: x ** 2, num_list)))# 解釋說明: map()傳入的第一個參數(shù)是一個匿名函數(shù) # 由于結果r是一個Iterator,Iterator是惰性序列,因此通過list()函數(shù)讓它把整個序列都計算出來并返回一個list。# map()作為高階函數(shù),事實上它把運算規(guī)則抽象了,因此,我們不但可以計算簡單的f(x)=x2,還可以計算任意復雜的函數(shù),比如,把這個list所有數(shù)字轉為字符串: print(list(map(str, num_list)))""" 再看reduce的用法。reduce把一個函數(shù)作用在一個序列[x1, x2, x3, ...]上,這個函數(shù)必須接收兩個參數(shù), reduce把結果繼續(xù)和序列的下一個元素做累積計算,其效果就是: reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) """ # 例子: 對一個序列求和 注意reduce不是python內置的 在functools模塊中 print(reduce(lambda a, b: a + b, [1, 3, 5, 7, 9])) # 這里的話其實可以直接使用sum() # 但是如果想把[1, 3, 5, 7, 9]變成13579 高階函數(shù)reduce就可以派上用場了 print(reduce(lambda a, b: a * 10 + b, [1, 3, 5, 7, 9])) # 第一次:1*10+3 -->13 # 第二次:13*10+5 -->135 # 第三次:135*10+7 -->1357 # 第四次:1357*10+9 -->13579# 利用map()函數(shù),把用戶輸入的不規(guī)范的英文名字,變?yōu)槭鬃帜复髮?#xff0c;其他小寫的規(guī)范名字。 # 輸入: ['adam', 'LISA', 'barT'],輸出: ['Adam', 'Lisa', 'Bart'] print(list(map(lambda x: x.capitalize(), ['adam', 'LISA', 'barT'])))# Python提供的sum()函數(shù)可以接受一個list并求和,請編寫一個prod()函數(shù),可以接受一個list并利用reduce()求積: def prod(num_list2):return reduce(lambda x, y: x * y, num_list2)print(prod([3, 5, 7, 9]))""" Python內建的filter()函數(shù)用于過濾序列。 和map()類似,filter()也接收一個函數(shù)和一個序列。和map()不同的是,filter()把傳入的函數(shù)依次作用于每個元素, 然后根據(jù)返回值是True還是False決定保留還是丟棄該元素。 """ # 在一個list中,刪掉偶數(shù),只保留奇數(shù) print(list(filter(lambda x: True if x % 2 != 0 else False, [1, 2, 3, 4, 5, 6, 7, 8, 9])))""" 排序也是在程序中經常用到的算法。無論使用冒泡排序還是快速排序,排序的核心是比較兩個元素的大小。 如果是數(shù)字,我們可以直接比較,但如果是字符串或者兩個dict呢?直接比較數(shù)學上的大小是沒有意義的,因此,比較的過程必須通過函數(shù)抽象出來。 Python內置的sorted()函數(shù)就可以對list進行排序: """ print(sorted([36, 5, -12, 9, -21])) # 默認是升序排列 可以通過reverse來控制 print(sorted([36, 5, -12, 9, -21], reverse=False)) # 默認是升序排列 即reverse=False print(sorted([36, 5, -12, 9, -21], reverse=True)) # reverse=True 降序排列""" 此外,sorted()函數(shù)也是一個高階函數(shù),它還可以接收一個key函數(shù)來實現(xiàn)自定義的排序,例如按絕對值大小排序: """ print(sorted([36, 5, -12, 9, -21], key=abs)) print(sorted([36,?5,?-12,?9,?-21],?key=abs,?reverse=True))程序運行結果如下:
分享或在看是對我最大的支持?
總結
以上是生活随笔為你收集整理的50 道 Python 基础练习题(附答案详解)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Rockchip开发系列 - 3.1.G
- 下一篇: Spring IOC(Inversion