程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python學習筆記_Day05

編輯:Python

列錶

>>> alist = [10, 5, 32, 1, 8, 20]
>>> alist[0] = 100
>>> alist[1:3] = [45, 88, 12, 24]
>>> alist
[100, 45, 88, 12, 24, 1, 8, 20]
>>> alist[2:2]
[]
>>> alist[2:2] = [12, 8]
>>> alist
[100, 45, 12, 8, 88, 12, 24, 1, 8, 20]
# 列錶的方法
>>> alist.append(12) # 追加
>>> alist.extend([55, 32, 1]) # 加入多項
>>> alist.remove(8) # 移除第一個8
>>> alist.index(12) # 返回第一個12的下標
>>> alist.reverse() # 翻轉
>>> blist = alist.copy() # 將alist的值copy後,賦值給blist
>>> alist.insert(2, 88) # 在下標為2的比特置插入88
>>> alist.sort() # 昇序排列
>>> alist.sort(reverse=True) # 降序
>>> alist.count(12) # 統計12出現的次數
>>> alist.pop() # 將最後一項彈出
>>> alist.pop(2) # 彈出下標為2的項目

元組

相當於是靜態的列錶。

>>> atuple = (10, 20, 15)
>>> atuple.count(10) # 統計10出現的次數
1
>>> atuple.index(15) # 獲取15的下標
2
>>> a = (10)
>>> type(a) <class 'int'>
>>> a
10
>>> b = (10,) # 單元素元組必須有逗號
>>> type(b) <class 'tuple'>
>>> len(b)
1

練習:模擬棧結構

  1. 棧是一個後進先出的結構
  2. 編寫一個程序,用列錶實現棧結構
  3. 需要支持壓棧、出棧、查詢功能
  4. 思考程序的運作方式
(0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 2
[]
(0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 0
數據: hello
(0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 0
數據: world #後進先出(後寫進去的內容先被取出 ) (0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 2 ['hello', 'world'] (0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 1
從棧中彈出: world
(0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 2 ['hello'] (0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 1
從棧中彈出: hello
(0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 1
空棧
(0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): 3
bye-bye
  1. 思考程序有哪些功能,將功能定義成函數
def push_it(): #壓棧
def pop_it(): #出棧
def view_it(): #查詢
def show_menu(): #所有實現功能的其他判斷語句匯總成一個函數
if __name__ == '__main__':
show_menu()

3.在各個函數中編寫具體的功能語句

第一種方法:
stack = []
def push_it():
data = input('請輸入數據:').strip()
if data:
stack.append(data)
else:
print('數據為空,未添加')
def pop_it():
if stack:
print('從棧中彈出: %s' % stack.pop())
else:
print('空棧')
def view_it():
print(stack)
def show_menu():
prompt = '''
(0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3):'''
while True:
choice = input(prompt).strip()
if choice not in ['0','1','2','3']:
print('無效輸入,請重試!')
continue
if choice == '0':
push_it()
elif choice == '1':
pop_it()
elif choice == '2':
view_it()
else:
print('Bye_bye')
break
if __name__ == '__main__':
show_menu()
第二種方法(使用字典):
stack = []
def push_it():
data = input('數據: ').strip()
if data:
stack.append(data)
else:
print('數據為空,未添加 ')
def pop_it():
if stack:
print('從棧中彈出: %s' % stack.pop())
else:
print('空棧')
def view_it():
print(stack)
def show_menu():
# 字典是容器類型,可以把任意對象存入,本例中存入函數
cmds = {'0': push_it, '1': pop_it, '2': view_it}
prompt = """(0) 壓棧
(1) 出棧
(2) 查詢
(3) 退出
請選擇(0/1/2/3): """
while True:
choice = input(prompt).strip() # 去掉字符串兩端空白字符
if choice not in ['0', '1', '2', '3']:
print('無效輸入,請重試。 ')
continue
if choice == '3':
print('Bye-bye')
break
cmds[choice]() # 在字典中取出相應的函數進行調用
if __name__ == '__main__':
show_menu()

字典

  • 映射、可變、容器
  • 字典key不能重複
  • 為字典賦值時,key存在則修改,不存在則新建
  • 字典的key必須是不可變對象
>>> dict(['ab', ['name', 'bob'], ('age', 20)])
{'a': 'b', 'name': 'bob', 'age': 20}
>>> dict([('name', 'tom'), ('age', 20), ('mail', '[email protected]')])
{'name': 'tom', 'age': 20, 'mail': '[email protected]'}
>>> {}.fromkeys(['tom', 'jerry', 'bob'], 20)
{'tom': 20, 'jerry': 20, 'bob': 20}
>>> info = dict([('name', 'tom'), ('age', 20), ('mail', '[email protected]')])
>>> info
{'name': 'tom', 'age': 20, 'mail': '[email protected]'}
>>> for key in info:
... print(key, info[key])
...
name tom
age 20
mail [email protected]
>>> '%(name)s is %(age)s years old' % info
'tom is 20 years old'
>>> '%s is %s years old' % (info['name'], info['age'])
'tom is 20 years old'
>>> info['age'] = 22
>>> info['phone'] = '15012345678'
>>> info
{'name': 'tom', 'age': 22, 'mail': '[email protected]', 'phone': '15012345678'}
>>> 'tom' in info
False
>>> 'name' in info
True
>>> len(info) 4
>>> info.keys() # 取出所有的key
dict_keys(['name', 'age', 'mail', 'phone'])
>>> info.values() # 取出所有的value
dict_values(['tom', 22, '[email protected]', '15012345678'])
>>> info.items() # 取出鍵值對
dict_items([('name', 'tom'), ('age', 22), ('mail', '[email protected]'), ('phone',
'15012345678')])
>>> list(info.items()) # 將鍵值對轉成列錶
[('name', 'tom'), ('age', 22), ('mail', '[email protected]'), ('phone', '15012345678')]
>>> info.popitem() # 彈出字典中的一項
('phone', '15012345678')
>>> info.pop('mail') # 彈出key是mail的項目
>>> info.update({'mail': '[email protected]'}) # 更新字典
>>> {(1, 2): 'tom'} # 元組作為key
{(1, 2): 'tom'}
>>> {[1, 2]: 'tom'} # 列錶是可變的,不能成為 key,報錯
# **字典中最重要的方法 **
>>> info.get('name') # 在字典中取出key為name的值
'tom'
>>> print(info.get('phone')) # key不在字典中,默認返回 None
None
>>> print(info.get('phone', 'not found')) # 找不到key返回not found
not found
>>> info.get('name', 'not found')
'tom'
>>> print(info.get('phone', '110'))
110

案例2:模擬用戶登陸信息系統

  1. 支持新用戶注冊,新用戶名和密碼注冊到字典中
  2. 支持老用戶登陸,用戶名和密碼正確提示登陸成功
  3. 主程序通過循環詢問進行何種操作,根據用戶的選擇,執行注冊或是登陸操作
import getpass
userdb = {} # 用於存儲用戶名和密碼
def register():
username = input('用戶名: ').strip()
if username == '':
print('用戶名不能為空 ')
elif not username.isalnum():
print('用戶名只能包含字母和數字 ')
elif username in userdb:
print('用戶已存在')
else:
password = input('密碼: ')
userdb[username] = password
def login():
username = input('用戶名: ').strip()
password = getpass.getpass('密碼: ').strip()
# if username not in userdb or userdb[username] != password:
if userdb.get(username) != password:
print('\033[31;1m登陸失敗\033[0m')
else:
print('\033[32;1m登陸成功\033[0m')
def show_menu():
cmds = {'0': register, '1': login}
prompt = """(0) 注冊
(1) 登陸
(2) 退出
請選擇(0/1/2): """
while True:
choice = input(prompt).strip()
if choice not in ['0', '1', '2']:
print('無效的選擇,請重試。 ')
continue
if choice == '2':
print('Bye-bye')
break
cmds[choice]()
if __name__ == '__main__':
show_menu()
驗證:
# python 05.py
(0) 注冊
(1) 登陸
(2) 退出
請選擇(0/1/2): 0
用戶名:lss
密碼:123
(0) 注冊
(1) 登陸
(2) 退出
請選擇(0/1/2): 1
用戶名: lss
密碼:
登陸成功
(0) 注冊
(1) 登陸
(2) 退出
請選擇(0/1/2): 2
Bye-bye

集合

集合是一個數學上的概念

  • 它由不同元素構成
  • 集合元素必須是不可變對象
  • 集合是無序的
  • 集合就像是一個無值的字典
  • 集合分成可變集合和不可變集合
>>> frozenset('abc') # 不可變集合,集合一旦創建,不能做增刪改操作
frozenset({'b', 'a', 'c'})
>>> set(['tom', 'jerry', 'bob'])
{'jerry', 'tom', 'bob'}
>>> aset = set('abc')
>>> bset = set('bcd')
>>> aset
{'b', 'a', 'c'}
>>> bset
{'b', 'd', 'c'}
>>> aset & bset # 交集,兩個集合中都有的元素
{'b', 'c'}
>>> aset | bset # 並集,兩個集合中所有的元素
{'b', 'd', 'a', 'c'}
>>> aset - bset # 差補,aset中有,bset中無
{'a'}
>>> bset - aset # 差補,bset中有,aset中無
{'d'}
>>> aset
{'b', 'a', 'c'}
>>> len(aset)
3
>>> 'a' in aset
True
>>> for ch in aset:
... print(ch)
>>> aset.add(10) # 向集合中加入新項目
>>> aset.pop() # 彈出任意一個元素
'b'
>>> aset.remove(10) # 刪除指定的元素
>>> aset.update(['tom', 'jerry', 'bob'])
>>> aset
{'tom', 'a', 'jerry', 'bob', 'c'}
>>> aset = set('abc')
>>> bset = set('bcd')
>>> aset.union(bset) # aset | bset
{'b', 'd', 'a', 'c'}
>>> aset.intersection(bset) # aset & bset
{'b', 'c'}
>>> aset.difference(bset) # aset - bset
{'a'}
>>> cset = aset.union(bset)
>>> aset.issubset(cset) # aset是cset的子集嗎?
True
>>> cset.issuperset(aset) # cset是aset的超集嗎?
True
# 經常使用集合實現去重操作
>>> from random import randint
>>> nums = [randint(1, 20) for i in range(20)]
>>> nums
[6, 12, 18, 19, 1, 1, 16, 15, 5, 6, 18, 19, 14, 11, 17, 13, 2, 5, 20, 16]
>>> result = []
>>> for i in nums:
... if i not in result:
... result.append(i)
>>> result
[6, 12, 18, 19, 1, 16, 15, 5, 14, 11, 17, 13, 2, 20]
>>> list(set(nums))
[1, 2, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

練習:

  • 模擬unix2dos程序
  • windows系統把\r\n作為行結束標志
  • 非windows系統把\n作為行結束標志

python l2w.py userdb.py =>生成新文件,已經具有windows的換行符

"""
轉換為windows換行格式
把源文件的每行結尾的空白字符刪除,再拼接上 \r\n
"""
---->解決的是linux上的文本文件拿到 windows上打開後就成一行顯示 ,沒有回車,需要將文本文件轉換後即
可.
import sys
def unix2dos(src, dst):
with open(src) as src_fobj:
with open(dst, 'w') as dst_fobj:
for line in src_fobj:
line = line.rstrip() + '\r\n'
dst_fobj.write(line)
if __name__ == '__main__':
unix2dos(sys.argv[1], sys.argv[2])

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved