#!/bin/env python3
#-*- coding:utf8 -*-
#學python3的第五天
#早晨時刻
# a = input('data: ')
# for i in a:
# if i not in '0123456789':
# print(False)
# break
# else:
# print('不是數字')
# alist = [1,2,3,4,5]
# print(alist)
# alist[0] = 100
# print(alist)
# print(alist[1:3]) #切片取值
# alist[1:3] = [9,6,9,5,9,200]
# print(alist)
# # 列表方法
# #追加
# alist.append(1000)
# print(alist)
# alist.append((1,2)) #把元組追加到列表
# print(alist)
# alist.extend((1,2)) #將序列中的每一項作爲列表項加入
# print(alist)
# alist.remove((1,2)) #將列表中的元組項刪除
# print(alist)
# a =alist.index(1000) #取出1000項的下表
# print(a)
# alist.reverse() #反轉列表
# print(alist)
# print(list(enumerate(alist))) #以key:value形式列出下標和對應項
# for x,y in list(enumerate(alist)):
# print(x,y)
# alist.insert(2,9) #在下標爲2的位置插入數據9
# alist.sort() #升序排列
# print(alist)
# alist.sort(reverse=True) #降序排列(利用了反轉)
# print(alist)
# alist.count(9) #統計9出現的次數
# print(alist.count(9))
# alist.pop() #彈出數據(默認將最後一個數據彈出)
# print(alist)
# alist.pop(2) #彈出下標爲2的數據項
# print(alist)
# blist = alist.copy() #講alist值拷貝出來賦值給blist(指向不同空間)
# print(blist)
# blist.clear() #清空列表
# print(blist)
# atu = (10,20,30)
# atu.count(100)
# print(atu.count(100)) #統計有幾個100
# atu.index(30)
# print(atu.index(30)) #看30的下標
# #單元素元組必須加逗號
# a = (10)
# print(type(a)) #是int型
# a = (10,) #是tuple元組
# print(type(a))
# print(len(a)) #這是一項
#案例1:用列表構建棧的結構
'''
(0)壓棧
(1)出棧
(2)查詢
(3)退出
請選擇(0/1/2/3):
'''
# #2.分析程序功能,將功能編寫成函數
# #3.編寫主程序代碼
#
# stack = []
#
# def push_it():
# #讀取用戶輸入,非空內容追加到列表,否則打印提示
# data = input('數據: ').strip() #去除兩邊空白
# if data: #如果data非空
# stack.append(data)
# print('寫入棧中數據: %s' % stack)
# 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 1:
# #將用戶輸入字符去除兩端空白字符,賦值給choice
# choice = input(prompt).strip()
# if choice not in ['0','1','2','3']:
# print('Please re-enter:input is not value!')
# continue
#
# if choice == '0':
# push_it()
# elif choice == '1':
# pop_it()
# elif choice == '2':
# view_it()
# else:
# print('\nBye-bye')
# break
#
# if __name__ == '__main__':
# show_menu()
# #*************優化版本***************
# stack = []
#
# def push_it():
# #讀取用戶輸入,非空內容追加到列表,否則打印提示
# data = input('數據: ').strip() #去除兩邊空白
# if data: #如果data非空
# stack.append(data)
# print('寫入棧中數據: %s' % stack)
# 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 1:
# #將用戶輸入字符去除兩端空白字符,賦值給choice
# choice = input(prompt).strip()
# if choice not in ['0','1','2','3']:
# print('Please re-enter:input is not value!')
# continue
#
# if choice == '3':
# print('\nBye-bye')
# break
#
# cmds[choice]()
#
# if __name__ == '__main__':
# show_menu()
#=========午間練習===========
# #!/bin/env python3
# #-*- coding:utf8 -*-
# stack = []
#
# '功能模塊區'
# def push_it():
# data = input('數據: ').strip() #消除兩邊空白行
# if data: #data非空執行
# stack.append(data)
# else:
# print('輸入內容爲空.')
#
# def pop_it():
# if stack:
# print('從棧中,彈出: %'% stack.pop()) #在輸出操作時候並執行彈出操作
# else:
# print('空棧')
#
# def view_it():
# print(stack)
#
# def show_menu():
# prompt = """(0)壓棧
# (1)出棧
# (2)查詢
# (3)退出
# 請選擇(0/1/2/3): """
#
# while 1:
# 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('\nBye-bye')
# break
#
# if __name__ == '__main__':
# show_menu()
#改良版本
#!/bin/env python3
#-*- coding:utf8 -*-
# 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 1:
# choice = input(prompt).strip()
# if choice not in ['0','1','2','3']:
# print('無效的輸入,請重試.')
# continue
#
# if choice == '3':
# print('\nBye-bye')
# break
#
# cmds[choice]()
#
# if __name__ == '__main__':
# show_menu()
# #字典:容器 可變 映射
# #key 不能重複 不可變類型
# #dict 字符串 元組 列表都可以寫入(必須只有兩個元素
# adict = dict(['ad',('name','bob'),['age',20]]) #dict創建字典的函數
# print(adict)
# #創建具有相同值的字典
# bdict = {}.fromkeys(['bob','alice','tom'],7)
# print(bdict)
# #利用for循環找到key的值
# for key in adict:
# print(key,adict[key])
# #也可以用%s替換做
# a = '%(name)s is %(age)d years old' % adict
# print(a)
#
# #賦值時,key在字典裏就會更新 不在則會添加
# adict['age'] = 22
# print(adict)
# adict['email'] = '[email protected]'
# print(adict)
# #成員關係判斷
# print('bob' in adict)
# print('name' in adict) #name是字典的key麼?
# print(len(adict))
# #字典的方法
# #如果字典裏存在 那麼二者無區別
# a = adict.get('age')
# b = adict['age']
# print(a,b)
# #如果字典裏不存在
# a = adict.get('bcz') #不會報錯 返回None(用函數取值)
# b = adict['bcz'] #沒有直接報錯(直接取值)
# print(a,b)
# #keys獲得所有key
# bdict = {}.fromkeys(['bob','alice','tom'],7)
# ak = bdict.keys()
# print(ak)
# #取出所有的value
# av = bdict.values()
# print(av)
# #取出key,value對
# keva = list(bdict.items())
# print(keva)
# '''keva排列'''
# print('key:','\t','value:')
# for i in keva:
# for x in i:
# print(x,'\t ',end='')
# print()
# #案例2:模擬用戶登錄信息系統
# #!/bin/env python3
# #-*- coding:utf8 -*-
# import getpass
#
# usrdb = {}
#
# def register(): #註冊
# username = input('\033[1;32m註冊用戶名:\033[0m ').strip()
# if username and (username not in usrdb): #可以加上括號提高可讀性
# password = input('\033[1;32m請輸入密碼:\033[0m ').strip()
# usrdb[username] = password
# if username in usrdb:
# print("\033[1;36m註冊成功!\033[0m")
# else:
# print("\033[1;31註冊失敗!\033[0m")
# else:
# print('用戶名爲空或已存在!')
#
# def login(): #登錄
# username = input('\033[1;33m輸入用戶名:\033[0m ').strip()
# password = getpass.getpass('\033[33;1m請輸入密碼:\033[0m ').strip()
# #if (username in usrdb) and (usrdb[username] == password):
# if usrdb.get(username) == password: #利用get取出密碼(如果不存在不會報錯回取出來None)
# print('\033[1;36m歡迎 %s回來!\033[0m' % username)
# else:
# print('\033[1;31m用戶名或密碼錯誤!\033[0m')
#
# def show_menu():
# cmds = {'0': register,'1': login}
# prompt = """\033[1;35m(0)註冊用戶
# (1)登入系統
# (2)退出
# 請選擇(0/1/2):\033[0m """
# while 1:
# choice = input(prompt).strip()
# if choice not in ['0','1','2']:
# print('\033[1;31m無效的輸入,請重試!\033[0m')
# continue
#
# if choice == '2':
# print('\n\033[1;36mBye-bye\033[0m')
# break
#
# cmds[choice]()
#
# if __name__ == '__main__':
# show_menu()
# #集合:不可變 不可重複(如果有重複的就留一個) 無順序
# #集合就像一個沒有鍵值的鍵值對(和字典相比較)
# s1 = set('abc')
# s2 = set('bcd')
# s3 = set(['tom', 'jerry', 'bob', 'alice'])
# print(s1)
# print(s2)
# print(s3)
# print(set('hello'))
# #查看集合長度
# print(len(s3))
# #for循環打印集合內容
# for name in s3:
# print(name)
# #集合可做成員關係判斷
# print('tom' in s3)
# print('zhangsan' in s3)
# print('zhangsna' not in s3)
# #集合工具:交集 並集 差補(常用三種方式)
# #交集:共有的
# print(s1 & s2)
# #並集:合併
# print(s1 | s2) #集合不可重複(重複的視爲多餘去除了)
# #差補:其中一個有的
# print(s1 - s2)
# #集合添加成員
# s3 = set() #添加空集合
# s3.add(10) #向集合中加10數據
# print(s3)
# #print(s3.add([20,30])) #錯誤,因爲列表是可變的
# s3.update([20,30]) #成功,因爲字典可變
# print(s3)
# #刪除元素
# s3.remove(30)
# print(s3)
# s4 = set((10 ,20 ,30,40))
# print(s4)
#
# #子集:被包含的集合
# s3.issubset(s4) #s3是s4的子集麼?
# print(s3.issubset(s4))
# #超集:包含子集的集合
# s4.issuperset(s3) #s4是s3的超集麼?
# print(s4.issuperset(s3))
# #集合的 交集 並集 差補函數
# print(s1.intersection(s2)) #s1 & s2
# print(s1.union(s2)) #s1 | s2
# print(s1.difference(s2)) #s1 -s2
# #集合的應用
# #去重複
# from random import randint
# nums = [randint(1,20) for i in range(20)]
# print(nums)
# print(set(nums))
# print(list(set(nums)))
#
# #日誌去重url
# with open('/tmp/mima1') as f1:
# s1 = set(f1)
# with open('/tmp/mima2') as f2:
# s2 = set(f2)
# with open('/tmp/mima3','w') as f3:
# f3.writelines(s2 - s1)
# alist = [10, 8 ,20 ,365 ,23, 4]
# print("%s is %s years old" % ('bob',23)) #常用
# print("%s is %d years old" % ('bob',23)) #常用
# print('%s is %d years old' % ('bob',23.5)) #%d是整數常用(打印不會顯示小數)
# #?print('%s is %5.2f years old' % ('bob',23.5)) #%5.2f是寬度爲5,2位小數(寬度寫不寫看起來沒區別)
# print('97 is %c' % 97) #acci碼中97爲小寫a編號
# print('11 is %#o' % 11) #表示有前綴的八進制
# print('11 is %#x' % 11)
# print('%10s%5s'% ('name','age')) #表示總寬度爲10,右對齊,常用
# print('%10s%5s'% ('bob',25))
# print('%10s%5s'% ('alice',23))
# print('%-10s%-5s'% ('bob',25)) #表示左對齊,常用
# print('%10d'%123) #寬度爲10默認空格補全
# print('%010d'% 123) #寬度爲10 改用0補全
#
# print('{} is {} years old'.format('bob',25))
# print('{1} is {0} years old'.format(25,'bob'))
# print("{:<10}{:<8}".format('name','age'))
# import shutil
#
# with open('/etc/password','rb') as sfobj:
# with open('/tmp/mima.txt','wb') as dfobj:
# shutil.copyfileobj(sfobj,dfobj) #拷貝文件對象
#
# shutil.copyfile('/etc/password','/tmp/mima2.txt')
# shutil.copy('/etc/shadow','/tmp/') #cp /etc/shadow /tmp/
# shutil.copy2('/ect/shadow','/tmp/') #cp -p /etc/shadow /tmp/
# shutil.move('/tmp/mima.txt','/var/tmp/') #mv /tmp/mima.txt /var/tmp
# shutil.copytree('/etc/security','/tmp/anquan') #cp -r /etc/security /tmp/anquan
# shutil.rmtree('/tmp/anquan') #rm -rf /tmp/anquan
# #講mima2.txt的權限設置成與/etc/shadow一樣
# shutil.copymode('/etc/shadow','/tmp/mima2.txt')
# #將mima2.txt的元數據設置成與/etc/shadow一樣
# #元數據使用stat /etc/shadow查看
# shutil.copystat('/etc/shadow','/tmp/mima2.txt')
# shutil.chown('/tmp/mima2.txt',user='zhangsan',group='zhangsan')
# import os
#
# def get_fname():
# while True:
# fname = input('filename: ')
# if not os.path.exists(fname):
# break
# print('%s already exists.Try again'% fname)
#
# return fname
#
# def get_content():
# content = []
# print('輸入數據,輸入end結束')
# while True:
# line = input('>')
# if line == 'end':
# break
# content.append(line)
#
# return content
#
# def wfile(fname,content):
# with open(fname,'w')as fobj:
# fobj.writelines(content)
#
# if __name__ == '__main__':
# fname = get_fname()
# content = get_content()
# content = ['%s\n'% line for line in content]
# wfile(fname,content)
# alist = [1,2,3,'bob','alice']
# alist[0] = 10
# alist[1:3] = [20,30]
# alist[2:2]= [22 ,24 ,26 ,28]
# print(alist)
# alist.append(100)
# alist.remove(24) #刪除的一個24
# alist.index('bob') #返回下標
# blist = alist.copy() #相當於blist = alist[:]
# alist.insert(1,15) #向下標爲1的位置插入數字15
# alist.pop() #默認彈出最後一項
# alist.pop(2) #彈出下標爲2的項目
# alist.pop(alist.index('bob'))
# alist = [1,2,3,0,-1]
# print(alist.sort()) #升序排列
# alist.reverse() #反轉
# alist.sort(reverse=True) #倒敘排列
# alist.count(20) #統計20在列表中出現的次數
# alist.clear() #清空
# alist.append('new')
# alist.extend('new')
# print(alist)
# alist.extend(['hello','world','hehe']) #會把每一項加進列表
# print(alist)
# import sys
# import keyword #檢查合法字符模塊
# import string
#
# first_chs = string.ascii_letters + '_'
# all_chs = first_chs + string.digits
#
# def check_id(idt): #由sys.arvg交互而得到變量賦值給idt(智能交互終端)
# if keyword.iskeyword(idt):
# return "%s is keyword" % idt
#
# if idt[0] not in first_chs:
# return '1st invalid'
#
# for ind,ch in enumerate(idt[1:]):
# if ch not in all_chs:
# return 'char in postion #%s invalid' % (ind + 2)
#
# return '%s is valid' % idt
#
# if __name__ == '__main__':
# print(check_id(sys.argv[1])) #python3 chekcid py abc@123
#**************************************************************
# import subprocess
# import sys
# from randpass2 import randpass
#
# def adduser(username,password,fname):
# data="""user information:
# %s:%s
# """
# subprocess.call('useradd %s' % username,shell=True)
# subprocess.call(
# 'echo %s | password --stdin %s'% (password,username),
# shell=True
# )
# with open(fname,'a')as fobj:
# fobj.write(data % (username,password))
#
# if __name__ == '__main__':
# username = sys.argv[1]
# password = randpass()
# adduser(username,password,'/tmp/user.txt')
# #python3 adduser.py jhon
#*********************************************************
# stack = []
#
# def push_it():
# item = input('item to push: ')
# stack.append(item)
#
# def pop_it():
# if stack:
# print('from stack poped %s' % stack.pop())
#
# def view_it():
# print(stack)
#
# def show_menu():
# cmds = {'0': push_it,'1': pop_it,'2': view_it}
# prompt = """(0)push it
# (1)pop it
# (2)view it
# (3)exit
# Please input your choice(0/1/2/3): """
#
# while True:
# choice = input(prompt).strip()[0]
# if choice not in '0123':
# print('Invalid input,Try again.')
# continue
#
# if choice == '3':
# break
#
#
# cmds[choice]()
#
# if __name__ == '__main__':
# show_menu()
#**************************************************
# import sys
#
# def unix2doc(fname):
# dst_fname = fname + '.txt'
#
# with open(fname)as src_fobj:
# with open(dst_fname,'w')as dst_fobj:
# for line in src_fobj:
# line = line.rstrip()+ '\r\n'
# dst_fobj.write(line)
#
#
# if __name__ == '__main__':
# unix2doc(sys.argv[1])
#***************************************************
# import time
#
# length = 19
# count = 0
#
# while True:
# print('\r%s@%s'% ('#' * count,'#' * (length-count)),end='')
# try:
# time.sleep(0.3)
# except KeyboardInterrupt:
# print('\nBye-bye')
# break
# if count == length:
# count = 0
# count += 1
#*************************
# adict = dict() #{}
# dict(['ab','cd'])
# bdict = dict([('name','bob'),('age',25)])
# print({}.fromkeys(['zhangsan','list','wangwu'],11))
#
# for key in bdict:
# print('%s:%s'% (key,bdict[key]))
#
# print('%(name)s:%(age)s' % bdict)
#
# bdict['name'] ='tom'
# bdict['email'] = '[email protected]'
#
# del bdict['email']
# bdict.pop('age')
# bdict.clear()
一起學Python吧~Day05
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.