練習題
文件處理相關
-
編碼問題
-
請說明python2 與python3中的默認編碼是什么?
python2默認是ASCII碼,python3默認是utf-8
-
為什么會出現中文亂碼?你能列舉出現亂碼的情況有哪幾種?
sys.stdout.encoding,默認就是locale的編碼,print會用sys.stdout.encoding去encode()成字節流,交給terminal顯示。所以locale需要與terminal一致,才能正確print打印出中文。
sys.setdefaultencoding(‘utf8’),用於指定str.encode() str.decode()的默認編碼,默認是ascii。
以下幾種(local 為軟件運行時的語言環境):
終端為UTF-8,locale為zh_CN.GBK
終端為UTF-8,locale為zh_CN.UTF-8
終端為GBK,locale為zh_CN.GBK
終端為GBK,locale為zh_CN.UTF-8 -
如何進行編碼轉換?
字符串在python內部中是采用unicode的編碼方式,所以其他語言先decode轉換成unicode編碼,再encode轉換成utf8編碼。 -
#-*-coding:utf-8-*-
的作用是什么?
#coding:utf-8 #.py文件是什么編碼就需要告訴python用什么編碼去讀取這個.py文件。 -
解釋py2 bytes vs py3 bytes的區別
Python 2 將 strings 處理為原生的 bytes 類型,而不是 unicode(python2 str == bytes),
Python 3 所有的 strings 均是 unicode 類型(python2 中需要通過 unicode )
string -> encode -> bytes
bytes -> decode -> string
-
-
文件處理
-
r和rb的區別是什么?
r 讀模式
rb 二進制讀2.解釋一下以下三個參數的分別作用
open(f_name,'r',encoding="utf-8")
f_name 文件名
r 模式
encoding 編碼方式 -
函數:
函數使用
-
寫函數,計算傳入數字參數的和。(動態傳參)
def func_sum(x, y):
return x + y
或
lambda x,y:x+y -
寫函數,用戶傳入修改的文件名,與要修改的內容,執行函數,完成整個文件的批量修改操作
import os def modify_file(file_name,content,newstr): new_file_name = '%sfile_name' %'new.' f_new = open(new_file_name, 'w') if os.path.exists(file_name): with open(file_name,'r+') as f: for line in f: if content in line: line = line.replace(content, newstr) f_new.write(line) f_new.close() os.rename(new_file_name, file_name) else: exit('file is not exist !!!')
-
寫函數,檢查用戶傳入的對象(字符串、列表、元組)的每一個元素是否含有空內容。
def isNull(p_obj): for item in p_obj: if item.strip() == '': return True else: return False a = [' ','1','2'] b = ['5','1','2'] c = 'ab c' print(isNull(a)) print(isNull(c)) print(isNull(b))
-
寫函數,檢查傳入字典的每一個value的長度,如果大於2,那么僅保留前兩個長度的內容,並將新內容返回給調用者。
def two_len(**kwargs): for k, v in kwargs.items(): if len(v) > 2: kwargs[k] = v[:2] return kwargs print(two_len(x='12', y='345', c='byw'))
-
閉包
內部函數包含對外部作用域而非全局作用域變量的引用,該內部函數稱為閉包函數
-
寫函數,返回一個撲克牌列表,里面有52項,每一項是一個元組
-
例如:[(‘紅心’,2),(‘草花’,2), …(‘黑桃A’)]
def cards(): type_li = ['紅心', '草花', '黑桃','梅花'] num = list(range(2, 11)) num.extend('JQKA') return [(x, y) for x in type_li for y in num ] print(len(cards()), cards())
-
-
寫函數,傳入n個數,返回字典{‘max’:最大值,’min’:最小值}
def max_min_dic(*args): min_v = min(args) max_v = max(args) return {'max':max_v,'min':min_v} print(max_min_dic(2,3,6,7,9))
-
寫函數,傳入一個參數n,返回n的階乘
from functools import reduce def factorial(n): if n == 0: return 0 elif n == 1: return 1 else: return reduce(lambda x, y: x*y ,list(range(1, n))) print(factorial(5))
-
編寫裝飾器,為多個函數加上認證的功能(用戶的賬號密碼來源於文件),要求登錄成功一次,后續的函數都無需再輸入用戶名和密碼
user_dic={ 'user':None, 'is_authenticate':False } def read_file(): with open('USER.TXT','r') as f: s = f.read().strip(',') user_info = eval(s) return user_info def auth(user_info): username = input("account:").strip() password = input("password:").strip() print(user_info) if username in user_info['name'] and password in user_info['password']: print("success") user_dic['user'] = username user_dic['is_authenticate'] = True return user_dic else: print("Failure") return '' def login_required(func): def inner(*args, **kwargs): if args[0].get('is_authenticate'): ret = func(*args, **kwargs) else: exit('need authenticate') return ret return inner @login_required def print_info(acc_data): print('進入') user_info = read_file() user_data = auth(user_info) print(user_data) print_info(user_data)
生成器和迭代器
生成器有幾種方式獲取value?
`next和for循環
內置函數
-
用map來處理字符串列表,把列表中所有人都變成good,比方alex_good
-
name=['alex','wupeiqi','yuanhao','nezha'] print(list(map(lambda x:x+'good',name)))
-
用filter函數處理數字列表,將列表中所有的偶數篩選出來
num = [1,3,5,6,7,8] print(list(filter(lambda x:x%2==0,num)))
-
如下,每個小字典的name對應股票名字,shares對應多少股,price對應股票的價格
計算購買每支股票的總價
用filter過濾出,單價大於100的股票有哪些
portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] print([(item['name'],item['shares']*item['price']) for item in portfolio]) print(list(filter(lambda item:item['price']>100, portfolio)))
4.有列表 li = ['alex', 'egon', 'smith', 'pizza', 'alen'], 請將以字母“a”開頭的元素的首字母改為大寫字母;
li = ['alex', 'egon', 'smith', 'pizza', 'alen'] print([item.capitalize() if item.startswith('a') else item for item in li])
5.有如下程序, 請給出兩次調用
show_num
函數的執行結果,並說明為什么: -
num = 20 def show_num(x=num): print(x) show_num() num = 30 show_num() 20 20 如果函數收到的是一個不可變對象(比如數字、字符或者元組)的引用,就不能直接修改原始對象,相當於通過“傳值’來傳遞對象。
6. 有列表 li = ['alex', 'egon', 'smith', 'pizza', 'alen'], 請以列表中每個元素的第二個字母倒序排序
-
li = ['alex', 'egon', 'smith', 'pizza', 'alen'] print(list(sorted(li,key=lambda x :x[1],reverse=True)))
綜合
- 有名為
poetry.txt
的文件,其內容如下,請刪除第三行: -
""" 昔人已乘黃鶴去,此地空余黃鶴樓。 黃鶴一去不復返,白雲千載空悠悠。 晴川歷歷漢陽樹,芳草萋萋鸚鵡洲。 日暮鄉關何處是?煙波江上使人愁。 """ import os str = '晴川歷歷漢陽樹,芳草萋萋鸚鵡洲' f_name = 'poetry.txt' f_new_name = '%s.new'% f_name f_new = open(f_new_name,'w',encoding='utf-8') with open(f_name,'r', encoding='utf-8') as f: for line in f: if str in line: line = '' f_new.write(line) else: f_new.write(line) f_new.close() os.replace(f_new_name, f_name)
- 有名為
username.txt
的文件,其內容格式如下,寫一個程序,判斷該文件中是否存在"alex", 如果沒有,則將字符串"alex"添加到該文件末尾,否則提示用戶該用戶已存在 -
import os str = 'alex' f_name = 'username.txt' f_new_name = '%s.new'% f_name with open(f_name,'r+', encoding='utf-8') as f: for line in f: if str in line: print('the user {} already exist'.format(str)) break else: f.write('\n%s' % str)
-
有名為user_info.txt的文件,其內容格式如下,寫一個程序,刪除id為100003的行;
-
""" 有名為user_info.txt的文件,其內容格式如下,寫一個程序,刪除id為100003的行 pizza,100001 alex, 100002 egon, 100003 """ f_name = r'user_info.txt' f_new_name = '%s.new'%f_name del_id = '100001' f_new = open(f_new_name, 'w', encoding='utf-8') with open(f_name, 'r', encoding='utf-8') as f: for line in f: if del_id in line: pass else: f_new.write(line) f_new.close() os.replace(f_new_name,f_name)
-
有名為user_info.txt的文件,其內容格式如下,寫一個程序,將id為100002的用戶名修改為
alex li
; -
""" 有名為user_info.txt的文件,其內容格式如下,寫一個程序,將id為100002的用戶名修改為alex li pizza,100001 alex,100002 egon,100003 """ f_name = r'user_info.txt' f_new_name = '%s.new'%f_name update_id = '100002' update_name = 'alex li' f_new = open(f_new_name, 'w', encoding='utf-8') with open(f_name, 'r', encoding='utf-8') as f: for line in f: if update_id in line: line = ','.join([update_name, update_id]) f_new.write(line+'\n') else: f_new.write(line) f_new.close() os.replace(f_new_name,f_name)
-
寫一個計算每個程序執行時間的裝飾器;
-
import time from functools import wraps def timer(func): @wraps(func) def wrapper(*args,**kwargs): start = time.time() ret = func(*args, **kwargs) print('{} execute {}s'.format(func.__name__,time.time()-start)) return ret return wrapper @timer # fib = timer(fib) def fib(n): a, b = 0, 1 for i in range(n): print(b) a, b = b, a+b return b fib(100)
-
lambda是什么?請說說你曾在什么場景下使用lambda?
-
好處: 1.lambda函數比較輕便,即用即扔,適合完成只在一處使用的簡單功能 2.匿名函數,一般用來給filter,map這樣的函數式編程服務 3.作為回調函數,傳遞給某些應用,比如消息處理
-
題目:寫一個搖骰子游戲,要求用戶壓大小,賠率一賠一。
要求:三個骰子,搖大小,每次打印搖骰子數。
-
import random def roll_dice(numbers=3, points=None): """ 定義骰子,循環三次 :param numbers: :param points: :return: """ if points is None: points = [] print('----- 搖骰子 -----') while numbers > 0: point = random.randrange(1, 7) # print('roll dice is {}'.format(point)) points.append(point) numbers -= 1 return points def roll_result(total): """ 定義大小,三個大或者一個小兩個大。三個小或者兩個小一個大 :param total: :return: """ is_big = 11 <= total <= 18 is_small = 3 <= total <= 10 if is_big: return "big" elif is_small: return "small" def start_game(): money = 1000 while money > 0: print('----- 游戲開始 -----') choices = ['big', 'small'] your_choice = input("請下注, big or small") your_bet = input("下注金額:") if your_choice in choices: if your_bet.isdigit(): points = roll_dice() total = sum(points) you_win = your_choice == roll_result(total) if you_win: print("骰子點數", points, total) money += int(your_bet) print("恭喜, 你贏了%s元, 你現在的本金%s 元" % (your_bet, money)) else: print("骰子點數", points, total) money -= int(your_bet) print("很遺憾, 你輸了%s元, 你現在的本金%s 元" % (your_bet, money)) else: print('格式有誤,請重新輸入') else: print('格式有誤,請重新輸入') else: print("game over") start_game()