Python 基础知识
来源:互联网 发布:阿里分布式数据库 编辑:程序博客网 时间:2024/05/22 18:21
1 相关链接
官网 : https://www.python.org/
学习网站 :
- http://bbs.pythontab.com/forum.php
- http://www.pythontip.com/blog/
- https://www.codecademy.com/learn/python
- http://www.tutorialspoint.com/python/
2 基本知识
2.1 数据结构
2.1.1 元组 ()
基本操作: 拼接(+*),切片(基于索引)
t1 = (1,2,3)t2 = ('hi','py')t3 = t1+t2t4 = t1*2print 't3 is:',t3print 't4 is:',t4print 't1[1:]:',t1[1:]
输出 :
t3 is: (1, 2, 3, 'hi', 'py')t4 is: (1, 2, 3, 1, 2, 3)t1[1:]: (2, 3)
基本函数:x in tup,len(tup),tup.count(),tup.index,cmp(tup1,tup2),max(tup),min(tup),tuple(list)
note: 元组元素不可变
>>> t=(1,2,3)>>> >>> del t[2]Traceback (most recent call last): File "<pyshell#53>", line 1, in <module> del t[2]TypeError: 'tuple' object doesn't support item deletion>>> >>> >>> t[2]=4Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> t[2]=4TypeError: 'tuple' object does not support item assignment>>>
2.1.2 列表 []
基本操作:同上
基本函数:cmp(l1,l2),len(l),max(l),min(l),list(l)
l.append(x),l.count(x),l.extend(list),l.index(x),l.insert(index,x),l.pop(index),l.remove(x),l.reverse(),l.sort([fun])
Note: 可以通过 dir(list) 查询该类中定义的相关函数,同理对于 元组,用 dir(tuple),字典用 dir(dict)
列表解析:
l=[2+n for n in range(0,5)]l2 = [i for i in l if i>5]print 'l is:',lprint 'l2 is :',l2输出
l is: [2, 3, 4, 5, 6]l2 is : [6]
2.1.3 字典{}
存储的是键值对
>>> dic = {'a':1,'hi':'a'}>>> dic{'a': 1, 'hi': 'a'}>>> dic['hi']'a'相关函数 :cmp(dic1,dic2),len(dic),str(dic),
dic.items(),dic.keys(),dic.values(),dic.get(key),dic.pop(key),dic.pop(key),dic.clear(),dic.copy(),dic.fromkeys(s,t),dic.update()
2.1.4 字符串
相关函数
dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
查该模块相关函数用法:
>>> print(str.format.__doc__)S.format(*args, **kwargs) -> stringReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}').>>> print 'I have {num}{pets}'.format(num=0,pets='dog')I have 0dog>>>
2.2 流程控制
Python 是用缩进来标识代码块
if/elif/else
for
while
for a in 'hello': if 'l'==a: print 'found' break print 'letter is :',aprint 'quit'输出
letter is : hletter is : efoundquit
2.3 函数
import math def area(d=5): return d**2输出
>>> area()25
2.5 面向对象
class books: def __init__(self): self._writer = 'joy' self._field = 'math' self.__price = 5 #私有变量 def __str__(self): return 'books(%s,%s)'%(self._writer,self._field) def __repr__(self): return str(self) # 特性装饰器,指出是一个获取函数,不接受除self 以外的参数 @property def writer(self): return self._writer @writer.setter def writer(self,writer): self._writer=writer#继承class child_books(books): def __init__(self): self._writer = 'jim' self._field = 'child' def __repr__(self): return 'child_books(%s,%s)'%(self._writer,self._field)
输出
>>> b.writer'joy'>>> b.writer='jim'>>> b.writer'jim'>>> c = child_books()>>> cchild_books(jim,child)
2.6 文本文件的读写
import os#逐行读取def print_file1(fname): f = fopen(fname,'r') for line in f: print(line) fclose()#整个文本文件一起读取def print_file2(fname): f = fopen(fname,'r') print f.read() f.close#写文件def write_file1(fname): if os.path.isfile('test.txt'): print 'already exist' else: f = fopen('test.txt','w') f.write('quit,\n')#插入文件到文件开头def insert_title(title,fname): f = fopen(fname,'r+') temp = f.read() temp = title+'\n'+temp f.seek(0)#文件指针指向文件开头 f.write(temp)
2.7异常处理
def get_age(): while True: try: n = int(input('how old are u?')) return 0 except ValueError: print('please enter an intefer value') finally: print('done')
0 0
- python基础知识
- Python 基础知识
- Python 基础知识
- python基础知识
- python基础知识
- python基础知识
- python基础知识
- Python基础知识
- python基础知识
- python基础知识
- Python-基础知识
- python基础知识
- python基础知识
- Python基础知识
- python基础知识
- python基础知识
- python基础知识
- Python:基础知识
- [BZOJ2064]分裂(状压dp)
- 服务器状态码详解
- Android控件之-------RatingBar(学习笔记)
- 面试中的排序算法总结
- java Pull解析XML
- Python 基础知识
- Linux yum 命令
- 源码安装redis3.2.3并注册为系统服务
- lightOJ1341 Aladdin and the Flying Carpet(唯一分解)
- 判断一个变量类型是数组还是对象
- vmware10安装linux,vm10安装CentOS 6图文
- 大数相乘
- 算法竞赛入门经典第四章习题
- 程序员老黄历Java源码实现