一.python列表
list是處理和存放一組數據的列表
用法:
acclist.index() 調出list中內容位置
acclist.insert() (要插入的位置,插入的內容) list插入內容
acclist.remove(value) 指要刪除的list中的內容(找到的第一個value) acclist.count(‘value’) 查找list中有多少個value
acclist[4] = ‘value’ 更改某個位置的元素
acclist.pop() 移除list中最後一個value(刪除第8個用:acclist.pop(8))
acclist.reverse() 把listz中value前後位置顛倒
acclist.sort() 把list中value排序(先數字,在大寫字母,小寫字母)
acclist.append() 方法向列表的尾部添加一個新的元素
acclist.extend([list]) == acclist + a 只接受一個列表作爲參數,並將該參數的每個元素
列表切片:
acclist[x:y] 截取list中元素x~y
>>>acclist
[0, 1, 12, 14, 16, 18, 'alices', 'dong', 'sam','sam', 'shaw']
>>> acclist[4:7]
[16, 18, 'alices']
取列表最小值:
>>> a = [1,200,3,600]
>>>a.sort()
>>> a
[1, 3, 200,600]
>>>min(a)
1
>>>max(a)
600
元素的引用:
a、範圍引用:基本樣式[下限:上限:步長]
>>>print s1[:5] # 從開始到下標4 (下標5的元素不包括在內)
>>>prints1[2:] # 從下標2到最後
>>>prints1[0:5:2] # 從下標0到下標4 (下標5不包括在內),每隔2取一個元素(下標爲0,2,4的元素)
>>>prints1[2:0:-1] # 從下標2到下標1
b、尾部元素引用
>>>print s1[-1] # 序列最後一個元素
>>>prints1[-3] # 序列倒數第三個元素
c、字符串是一種特殊的元素,因此可以執行元組的相關操作
>>> str = 'abcdef'
>>> printstr[2:4]
d、如果s1[0:-1], 那麼最後一個元素不會被引用(即,不包括上限元素本身)
>>> s1 = (2, 1.3, 'love', 9, 12, False)
>>> prints1[0:-1]
(2, 1.3, 'love',9, 12)
例如:(取0-10之間偶數/奇數)
>>> c= [c for c in range(10)]
>>> c
[0, 1, 2, 3,4, 5, 6, 7, 8, 9]
>>>c[1: :2]
[1, 3, 5, 7,9]
>>>c[0: :2]
[0, 2, 4, 6,8]
由於list的元素可變更,你可以對list的某個元素賦值:
>>>s2[1] = 3.0
>>>print s2
[True, 3.0,'smile']
e、獲得表中元素個數
>>> shaw=['sam',21,67,'A']
>>>len(shaw)
4
小結:列表轉換成字符串
Python join() 方法用於將序列中的元素以指定的字符連接生成一個新的字符串
join()方法語法:
str.join(sequence)
實例:
#!/usr/bin/python str ="-"; seq =("a", "b", "c"); # 字符串序列 printstr.join( seq ); 結果: a-b-c
二.python字典
詞典和列表類似的地方,是包含有多個元素,每個元素以逗號分隔。但詞典的元素包含有兩部分,鍵和值,常見的是以字符串來表示鍵,也可以使用數字或者真值來表示鍵(不可變的對象可以作爲鍵)。值可以是任意對象。鍵和值兩者一一對應
創建字典:
>>> shaw = {'shaw':23, 'sam':28,'alices':22}
>>> print type(shaw)
<type 'dict'>
>>> print shaw['sam']
28
>>> shaw['alices']= 18
>>> print shaw
{'shaw': 23, 'sam': 28, 'alices': 18}
與列表不同的是,詞典的元素沒有順序。你不能通過下標引用元素。詞典是通過鍵來引用
字典添加新元素:
>>> dong = {'shaw':23,'sam':33}
>>> print dong
{'shaw': 23, 'sam': 33}
>>> dong['alex'] = 35
>>> print dong
{'alex': 35, 'shaw': 23, 'sam': 33}
字典常用方法:
>>>print dic.keys() # 返回dic所有的鍵
>>>print dic.values() # 返回dic所有的值
>>>print dic.items() # 返回dic所有的元素(鍵值對)
>>>dic.clear() # 清空dic,dict變爲{}
>>>del dic['tom'] # 刪除 dic 的‘tom’元素
>>>dic.popitem() # 默認刪除第一個
>>>dic.copy() # 拷貝字典
>>>dic.pop(key) # 刪除某個鍵值對
>>> shopinfo.has_key('Apple') # 查詢字典中是否有某鍵(返回Flase/True)
>>>dict.update(dict2) # 把字典dict2的鍵/值對更新到dict裏
>>>shopinfo.get('shaw') # 返回指定鍵的值,若沒有該鍵返回默認值(none)
>>>shipinfo.setdefault(‘a’:123) #如果dict中已有a,則不會被覆蓋
額外內容:
1、del是Python中保留的關鍵字,用於刪除對象
Python刪除列表,變量
Del [6:10]
Del a
Del 可以刪除所有類型變量內容和變量
2、與列表類似,你可以用len()查詢詞典中的元素總數
>>>print(len(dic))
3、str轉成list
>>> shaw = 'shaw 123'
>>> print shaw,type(shaw)
shaw 123 <type 'str'>
>>> shaw.split()
['shaw', '123']
4、list轉成str
''.join() ‘’之間字符,指定以什麼字符把列表拼接成字符串
>>> ling = ['shaw','sam']
>>> print ling,type(ling)
['shaw', 'sam'] <type 'list'>
>>> '-'.join(ling)
'shaw-sam'
5、python枚舉函數:(enumerate)
enumerate在循環時,可以同時訪問到當前str的索引值
>>> for key, value in enumerate('sdafsd'):printkey,value
...
0 s
1 d
2 a
3 f
4 s
5 d
6、Python isdigit()
檢測(判斷)字符串是否只由數字組成
#!/bin/env python # -*- coding:utf-8 -*- ''' @author: shaw ''' count = raw_input('please intput you age:').strip() print type(count) if count.isdigit(): count = int(count) print type(count) # 執行測試 please intput you age:999 <type 'str'> <type 'int'>
7、input
輸入什麼類型,input就會把輸入當做什麼類型來處理
8、python split() 字符串轉列表
#!/bin/env python
# -*- coding:utf-8 -*-
'''
@author: shaw
'''
name = 'shaw sam alex'
name = name.split() 什麼都不加,默認以空格區分
print name
['shaw', 'sam', 'alex']
三、Python模塊
import modulename
from module import sayhi 只導入某個模塊的某個方法
import modulename as NewName
Such as:
import os,sys
os.system('command') 執行結果的狀態值
os.popen('command') 執行結果
>>> import os,sys
>>> print os.popen('pwd').read()
/root
commands.getoutput('command') 執行系統命令
>>> import commands
>>> print commands.getoutput('pwd')
/root
sys.argv() 用來獲取命令行參數
四、python 文件處理
python支持中文:#_*_coding:utf-8_*_
f = file(文件名,模式)
模式:
'r' #只讀
'w' #寫入
'a' #追加(append)
比如:
>>>f= open("test.txt","r")
文件對象方法
讀取:
content = f.read(N) # 以“字符串”形式讀取N bytes的數據,(立刻把所有文件讀到內存)
content = f.readline() # 讀取一行(不會立刻把所有文件讀到內存)
content = f.readlines() # 讀取所有行(立刻把所有文件讀到內存),儲存在列表中,(很慢)
A = f.writelines #寫多行----(把)列表存到文件
Content = f.xreadlines() # 一行行讀取文件(不會立刻把所有文件讀到內存.很快)
寫入:
f.write('I like apple') # 將'I like apple'寫入文件
file.tell() #返回當前文件中的位置(讀到哪裏了)。獲得文件指針位置
file.seek(0) # 返回到文件開始位置(默認0)
file.truncate(size=80) 截取文件到80 size個字節,默認爲當前文件位置
f.flush() # 刷新文件內存緩衝,直接把內存緩衝區的數據立刻寫入文件, 而不是被動的等待輸出緩衝區寫入.
特殊方法:
f = file(‘shaw.txt’,’r+’) == withopen(‘shaw.txt’,’r+’) as f:
兩者區別:with open會自動關閉文件,不用f.close()
後者程序執行完,直接回車即可
修改文件內容:
import fileinput
for line infileinput.input('shaw.txt',inplace=1, backup='.bak'):
line = line.replace('The 4 loops','The shawloops')
print line,
inplace=1表示:替換文件之後,在寫入到源文件
inplace=0或者不寫,表示只打印替換後的文件內容,而源文件內容不變
backup='.bak' 表示,在改變源文件內容前,會備份源文件爲:x.bak
# 因爲是循環所以是全局替換
注意:如果對Python程序沒做字符聲明,默認情況下,它會以“ASCII”字符編碼方式處理程序內容。
Day-練習題:
購物車程序
要求用戶輸入工資,然後打印購物菜單
用戶可以不斷的購買商品,直到money not enough
退出時,格式化打印用戶已購買的商品和剩餘money
流程圖:
代碼:
#!/bin/env python #_*_coding:utf-8_*_ ''' @author: shaw ''' count = 0 shoplist = [] products = ['iphone','bike','notebook','letv','book'] money = [5980,288,4999,998,20] while count < 3: salary =raw_input('please input your salary:').strip() #如果工資字符類型輸錯3次,退出程序 if count>= 2: print'\033[1;31m#Info\033[0m you input error,bye!' break #判斷工資錄入數據是否全爲數字 if salary.isdigit(): salary= int(salary) while True: print 'The prodocts of list:' fori in products: print ' %s'%i,' \033[1;33m¥%s\033[0m'%money[products.index(i)] shoplisting=raw_input('what you want to buy:').strip() #判斷money是否足夠買所選商品 ifsalary < money[products.index(shoplisting)]: print '\033[1;31m### INFO:\033[0m' print' The balance is\033[1;31m%s\033[0m and not enough to shopping,bye !'%salary print ' shoplist:' for i in shoplist: print ' %s'%i,' ¥%s'%money[products.index(i)] count = 100 break salary = salary - money[products.index(shoplisting)] print 'The current balance is \033[0;32m%s\033[0m'%salary shoplist.append(shoplisting) else: print'\033[1;32m#Info\033[0m Please enter a number.' count+=1 if count ==100: break