您的位置:首页 > 编程语言 > Python开发

Python开发基础-day2

2016-01-25 11:45 776 查看
一.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到下标1b、尾部元素引用 >>>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 s1 d2 a3 f4 s5 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 fileinputfor 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


本文出自 “Shaw Blog” 博客,请务必保留此出处http://opsedu.blog.51cto.com/9265055/1738158
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: