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

python基础篇日记

2017-03-22 17:09 363 查看
 -----------------------------------------

1,基础篇。

#encoding=utf-8

#上面可以随便写的,只要符合oding=[]

#basic1.py          //相当于导入了asic1模块

                   #可以使用  basic1.new_str

#这里给下面语句做一个注释

new_str="这是一个全局变量" #注释

"""

这是一个标准脚本的写作格式,此处为脚本文档

"""

def hello():

    """

    此处为脚本程序的解释

    @author:李亚飞

    @copyright:归本人所有

    @version:1.0

    """

    return "hello world"

    

#一定要下一行空4格。

#程序主体:

#if语句判断是否是主程序

#调用其他函数时,要带上括号和参数

if __name__=="__main__":     

    print(hello())      #print hello()  提示SyntaxError: Missing parentheses in call to 'print'

    

print basic1.__doc__

基础篇6

>>> d=open('d:a.txt','w')       创建一个文件,以读的方式

>>> d.write("hghagd \n hage\n hadslae")         向文件中写入内容

>>> d.flush()                                   刷新

>>> d.close()                                   关闭

>>> d.open('d:a.txt','r')   错误,d已经关闭           

Traceback (most recent call last):

  File "<input>", line 1, in <module>

AttributeError: 'file' object has no attribute 'open'

>>> d=open('d:a.txt','r')         打开一个文件以写的方式

d.readline(3)     //一行读几个。

>>> d.readline()         一次读一行

'hghagd \n'

>>> d.read()             将剩余的读完

' hage\n hadslae' 

>>> d.seek(0)            #将d文件从头开始

>>> d.read(100)          #一次读多少字节

'hghagd \n hage\n hadslae'

>>> 

基础篇7

str="abc"不可变

str[0]=1  错误

arr=[1,3,5]  可变

arr[0]=3   正确

>>> a

'this is world'

>>> b=a.replace("this","that") 替换

>>> b

'that is world'

>>> b

'that is world'

>>> a

'this is world'

>>> a.find("is")      查询

2                     角标

>>> a.find("s")

3

>>> a.find('s',4,len(b)-1)

6             查询,后面跟起始结束位置

>>> a[6]

's'

>>> a.find(sub [,start[,end]])  其中sub为必填项,[]里面的为选填项。

%s   为字符串占位符,>>> a="this %s a %s world"%("is","beautiful")

                     >>> a

                    'this is a beautiful world'

format替换          >>> a="this {0} a {1} world".format("is","beautiful")

                    >>> a

                    'this is a beautiful world'

输入参数替换        >>> b="this {be} a {adj} world".format(adj="beautiful",be="is")

                    >>> b

                    'this is a beautiful world'

字典              >>> c="this %(be)s a %(adj)s world"%{'be':'is','adj':'beautiful'}

                   >>> c

                   'this is a beautiful world'

%d    为数字占位符

基础篇9列表

>>> a=[1,2,3]

>>> a

[1, 2, 3]

>>> a[0]

1

>>> a[-1]  最后一个值

3

>>> a[2]=7  替换

>>> a

[1, 2, 7]

列表的索引

>>> a=[1,2,4,5]

>>> a[0:4:1]      //正向索引

[1, 2, 4, 5]

>>> a[-1:-4:-1]  //反向索引

[5, 4, 2]

>>> a[:]

[1, 2, 4, 5]

>>> a[:3]       缺的就是结尾或者开头

[1, 2, 4]

>>> 

列表的添加

>>> a.append(7)             append 末尾添加

>>> a

[1, 2, 4, 5, 7]

>>> b=[3,65,7]

>>> a+b

[1, 2, 4, 5, 7, 3, 65, 7]

>>> a.extend(b)              extend添加

>>> a

[1, 2, 4, 5, 7, 3, 65, 7]

>>> a

[1, 2, 4, 5, 7, 3, 65, 7, 3, 65, 7, 3, 65, 7]

>>> a.insert(2,90)             insert//插入,可以控制插入位置

>>> a

[1, 2, 90, 4, 5, 7, 3, 65, 7, 3, 65, 7, 3, 65, 7]

>>> 

3,列表的修改

>>> a=[1,2,3]

>>> a[2]=7  替换

>>> a

[1, 2, 7]

4,列表的删除

>>> a

[1, 2, 90, 4, 5, 7, 3, 65, 7, 3, 65, 7, 3, 65, 7]

>>> del a[2]      del删除

>>> a

[1, 2, 4, 5, 7, 3, 65, 7, 3, 65, 7, 3, 65, 7]

>>> 

>>> a

[1, 4, 5, 7, 3, 65, 7, 3, 65, 7, 3, 65
f722
, 7]

>>> a.remove(7)    //删除第一个匹配的值

>>> a

[1, 4, 5, 3, 65, 7, 3, 65, 7, 3, 65, 7]

>>> 

>>> a

[1, 4, 5, 3, 65, 7, 3, 65, 7, 3, 65, 7]

>>> a.pop()       //pop删除最后一个元素并返回,和汇编中的弹栈pop相同

7

5,成员关系

使用关键字in,not in,返回值为true或false           //也可以判断集合之间是否相互包含等

>>> a

[1, 4, 5, 3, 65, 7, 3, 65, 7, 3, 65]

>>> 5 in a

True

>>> 2 in a                

False

>>> 2 not in a

True

>>> 

6列表推导式

[expr for iter_var in iterable]  [迭代表达式 for 迭代变量 in 迭代范围]

>>> [x for x in range(1,11)]     //迭代式

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> [3*x for x in range(1,11)]   //迭代式,表达式是变量的函数

[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

>>> [y for x in range(1,11)]

Traceback (most recent call last):

  File "<input>", line 1, in <module>

NameError: name 'y' is not defined

>>> [x for x in range(1,11) if x%2==0]  //只有满足表达式if ,才把数字放到迭代变量中

[2, 4, 6, 8, 10]

>>> 

7,排序,反转

sort,reverse

>>> a

[2, 3, 4, 4, 5, 6, 7, 7, 32]

>>> a.reverse()

>>> a

[32, 7, 7, 6, 5, 4, 4, 3, 2]

>>> a.sort()

>>> a

[2, 3, 4, 4, 5, 6, 7, 7, 32]

>>> 

基础篇第十节列表应用

1,list列表

>>> a="abc"

>>> b="def"

>>> c="jhk"

>>> list(a)            //集合,参数是一个可迭代对象

['a', 'b', 'c']     

>>> list([a,b,c])

['abc', 'def', 'jhk']

>>> list(a,b,c)               参量过多

Traceback (most recent call last):

  File "<input>", line 1, in <module>

TypeError: list() takes at most 1 argument (3 given)

>>> list([list(a),list(b),list(c)])

[['a', 'b', 'c'], ['d', 'e', 'f'], ['j', 'h', 'k']]   列表嵌套

>>> 

2,xrange 和range的应用,效果一样

>>> a=xrange(1,10,2)

>>> a

xrange(1, 11, 2)      生成一个xrange对象,可以省内存,只操作部分数据,一般用在循环里面,

>>> b=range(1,10)     生成一个列表对象

>>> b

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> a[0]

1

>>> a[4]

9

>>> 

例如:

for m in range(1000)  生成一个[1--999]

    if m==10

    print 'sss'

    break

for m in xrange(1000)   生成一个[1--10]

    if m==10

    print 'sss'

    break

//生成不只是数字

>>> ['the %s' % d for d in xrange(10)]

['the 0', 'the 1', 'the 2', 'the 3', 'the 4', 'the 5', 'the 6', 'the 7', 'the 8', 'the 9']

//生成列表

>>> [(x,y) for x in range(10) for y in range(2)]

[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1), (4, 0), (4, 1),

 (5, 0), (5, 1), (6, 0), (6, 1), (7, 0), (7, 1), (8, 0), (8, 1), (9, 0), (9, 1)]

//生成字典

>>> dict([(x,y) for x in range(10) for y in range(2)])

{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}  键相同将会覆盖,留下最后一个值

>>> 

>>> dict([(x,y) for x in range(10) for y in range(3)])

{0: 2, 1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2}

>>> 

>>> a = dict(one=1, two=2, three=3)

>>> b = {'one': 1, 'two': 2, 'three': 3}

>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))

>>> d = dict([('two', 2), ('one', 1), ('three', 3)])

>>> e = dict({'three': 3, 'one': 1, 'two': 2})

>>> a == b == c == d == e

True

-----------------------------------

>>> a

[3, 4, 5, 6, 7]

>>> random.shuffle(a)      //随机打乱列表

>>> a

[6, 7, 5, 3, 4]

>>> 

--------------------------------

//引用

>>> a=['hello','world']

>>> a

['hello', 'world']

>>> b=a

>>> a[1]='hello'

>>> a

['hello', 'hello']

>>> b

['hello', 'hello']

>>> del b[1]   直接删除元素

>>> a

['hello']

>>> 

>>> a

[1, 2, 3, 4]

>>> b=a

>>> del b  //删除引用,

>>> a

[1, 2, 3, 4]

>>> b

Traceback (most recent call last):

  File "<input>", line 1, in <module>

NameError: name 'b' is not defined

>>> 

第十一节 元组(tuple)和集合

1 有序的集合

2 通过偏移量来取数据

3, 属于不可变的对象,不能在原地修改内容

>>> a=(3,6,2)

>>> a

(3, 6, 2)

>>> a[0]

3

>>> a[1:3]

(6, 2)

>>> a[0]=4         //不可修改

Traceback (most recent call last):

  File "<input>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

>>> 

>>> b=list(a)  可以将元组改为列表,修改之后在变为元组

>>> b[0]=4

>>> a=tuple(b)

>>> a

(4, 6, 2)

>>> 

def info(a):               定义一个函数,顶格写,传入参数

    print 'id %d' % id(a)   按tab键,空4格

    a[0]='haha'             列表可以修改里面的元素,元组不可以修改

    return a

                             函数体要和其他语句隔一行

a=[1,2,3]

print id(a)

                             //执行函数要前后隔一行

info(a)

print a

>>> def info(a):   

...     print 'id %d' % id(a)       

...     a[0]='haha'

...     return a

...                

>>> a=[1,2,3]

>>> print id(a)

... 

158258960

>>> info(a)

... 

id 158258960

['haha', 2, 3]

>>> print a

['haha', 2, 3]

>>> 

集合;没有顺序

创建集合set()里面为空或可迭代的对象 :可变的,frozenset()不可变的,没有增删该

>>> a=[]       可迭代__iter__

>>> dir(a)

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 

'__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 

'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> a=()       可迭代__iter__

>>> dir(a)

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__',

 '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

>>> dir(2)     不可迭代

['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__',

 '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__',

 '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',

 '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

>>> 

>>> a=set("hdglg")

>>> a

set(['h', 'd', 'g', 'l'])  //生成set集合

>>> a=list("ehgh")

>>> a

['e', 'h', 'g', 'h']   //列表list

>>> 

>>> a=set('ehgil')

>>> a.add('python')   //添加

>>> a

set(['e', 'g', 'i', 'h', 'l', 'python'])  

>>> a.update('python')                      //更新

>>> a

set(['e', 'g', 'p', 'i', 'h', 'l', 'o', 'n', 'python', 't', 'y'])

>>> a.remove('python')                    //删除

>>> a

set(['e', 'g', 'p', 'i', 'h', 'l', 'o', 'n', 't', 'y'])

集合的交并差

>>> a=set('abcd')

>>> b=set('cdef')

>>> a & b

set(['c', 'd'])

>>> a | b

set(['a', 'c', 'b', 'e', 'd', 'f'])

>>> a-b

set(['a', 'b'])

>>> 

set去重  set集合中没有重复元素

>>> a=[1,2,3,7,5,2,3]

>>> set(a)

set([1, 2, 3, 5, 7])

>>> list(set(a))

[1, 2, 3, 5, 7]

>>> 

基础篇12 字典

字典是无序的,它不能通过偏移来存取,只能通过键来存取,可嵌套

键只能是不可变的数据类型,比如数字,字符串,元组(里面元素也要为不可变类型)。列表等不能作为键

>>> info={'a':1,'b':2}  字典:左边键右边值,可以存放多组

>>> info['a']            通过通过键取值

1

>>> binfo={'a':[1,23,3],'b':[3,25,6]}  //可嵌套

>>> binfo

{'a': [1, 23, 3], 'b': [3, 25, 6]}

>>> binfo['a'][2]=5                    //可在原地修改内容

>>> binfo

{'a': [1, 23, 5], 'b': [3, 25, 6]}

>>>

创建字典

info={'a':1,'b':2}

>>> a=dict(one=1,two=2)

>>> a

{'two': 2, 'one': 1}

>>> dict([(x,y) for x in range(10) for y in range(3)])

{0: 2, 1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2}

添加字典

>>> a=dict(one=1,two=2)

>>> a

{'two': 2, 'one': 1}

>>> a['three']=3

>>> a

{'three': 3, 'two': 2, 'one': 1}>>> 

a['two']=5  //修改

>>> a

{'three': 3, 'two': 5, 'one': 1}

>>> 

>>> a.update({'four':4,'one':9})          //添加修改,覆盖相同的键

>>> a

{'four': 4, 'three': 3, 'two': 5, 'one': 9}

>>> 

删除

>>> del a['one']   根据键删除值

>>> del a          删除

>>> a.clear()         删除字典的全部元素,剩余一个空字典

>>> a.pop('two')      删除该键,并返回改建的值,如果没有该键,可以指定相应的值a.pop('two','2')

in 和has_key()成员关系操作

>>> a=dict(one=1,two=2)

>>> a.has_key('one')

True

>>> 'one' in a

True

>>> 

keys():返回的是列表,里面包含了字典的所有键

values()返回的是列表,里面包含了字典的所有值

items:生成一个字典的容器  :[()]

>>> a=dict(one=1,two=2)

>>> a.items()

[('two', 2), ('one', 1)]

>>> 

7  get通过键获取值,如果是不存在的键名,返回一个nonetype类型

      输入一个不存在的键名,可以设置返回的默认值

 

13数据结构习题

   

14 特殊符号

   bin()将其他进制转化为2进制

  << 二进制左位移  >>二进制右位移,箭头朝那向哪移

  >>> bin(3<<4)

'0b110000'

   & 按位与   | 或     ^异或    ~取反   进行二进制的按位与,或,异或,取反

15 数据结构

   list:列表,可以通过下标取出元素,只能用数字作为下标   相当于java中的数组,但可变长度

   dict 键值对,键可以是任意不可变的元素 ,无序           相当于java中map     

   tuple 有序的集合,不可变的集合,不能在原地修改,可通过偏移量取数据     相当于java中的数组

   set集合,不含重复元素

   >>> a

(3, 4, 5, 7)

>>> b=list(a)  //元组转换为list

>>> b

[3, 4, 5, 7]

>>> tuple(b)    //list转换为tuple

(3, 4, 5, 7)

>>> b

[3, 4, 5, 7]

>>> c=[(1,2),(3,4),(7,3)]   //list转换为dict

>>> print dict(c)

{1: 2, 3: 4, 7: 3}

>>> 

>>> y=[y for y in range(10)]

>>> y

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> sorted(y,reverse=True)      sort内置方法

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

>>> 

>>> c

[('b', 3), ('a', 4), ('e', 9)]

>>> c.sort(key=lambda x:x[1],reverse=True)  //key=lambda x:x[1],x选择每个元组单元,x[1]每个元组单元按照角标为1的元素进行排序

>>> c

[('e', 9), ('a', 4), ('b', 3)]

>>> 

>>> a=[(1,2,3),(3,4,5),(6,3,2)]

>>> import operator

>>> a.sort(key=operator.itemgetter(1,2))  通过模块operator按照元组里面的角标1,2排序

>>> a

[(1, 2, 3), (6, 3, 2), (3, 4, 5)]

>>> 

基础篇16 python语句

 1,print语句

f=open('d:a.txt','w')    打开一个文件

print >> f,"heheehehliyafei"   使用重定向向f输入数据

f.close()

 2控制流语句

  if True: 条件,:分割了条件和代码块

    print 4        执行代码块,缩进4个空格

    //下面要空一行在函数中

3 bool值

  and 

  or 

  is 检查共享

  ==检查值

  not

  其他若干比较符号

4 if 语句

   if 

   elif

   else   pass

5 三元表达式 

  4 if True else 3   

  if True

     print 4

  eles 

     print 3

三元表达式[4,3][True]

基础篇17语句

  while expression

        statement

  berak 跳出循环

  continue 跳出本次循环,不跳出while

  else执行完while再执行else,当break终止while时,else不执行

  所以else不能和break合用

  当在命令行中while执行死循环时,按Ctrl+c跳出

  ulipad中注释Ctrl+?

  关闭注释:Ctrl+\

  按tab键可以调到${}部分

  

  for语句  for item in iterable  item迭代变量,iterable可迭代的集合,列表,字符串等

  for代码块执行完之后,最后一个迭代值保存到迭代变量中。

 >>> for item in [3,4,5]:

...     print item

...     

3

4

5  

continue 跳出本次循环,不跳出for

  else执行完for再执行else,当break终止for时,else不执行

  所以else不能和break合用

19语句与数据结构的应用

  

>>> b=dict(one=1,two=9)  字典

>>> print b

{'two': 9, 'one': 1}

>>> for i,j in b.items():  输出键值

...     print i,j

...     

two 9

one 1

dict1={'a':'jkl','l':'dkls','b':'akd','e':'alkd'}

key_list=dict1.keys()   取出键集合

key_list.sort()         键集合排序

for i in key_list:

    print i,dict1[i]  //根据键拿值

字典具有唯一键,但值是不一样的

一个值可能对应多个键

    

dict1={'a':'jkl','l':'dkls','b':'akd','e':'alkd'}

key_list1=[]

a='jkl'                  根据值拿键

for x,y in dict1.items:

    if y==a

        key_list1.append(x)

    

print key_list1

基础篇20函数  ,函数是一个方法,解决一个问题,一个对象有很多函数,可以解决很多问题

               , 一定要写文档,

def function(a,b):  //定义函数,def 冒号不可少,首行缩进4个格

    "注释"          两个双引号或者两个单引号,或者三个双引进行多行注释文档

    statement       //语句

function()          //调用函

    

print function.__doc__   //找出文档

def function1(a=4)://可选参数,可以更改,也可以不传。

函数内变量在外部无效

函数外变量,是全局变量

在函数中声明Global 全局变量 ,那么函数中定义的变量  使用的就是全局变量,修改之后,后面再用,和改变之后的值一样。

>>> list1=[1,2,3]

... 

>>> def func(l):

...     l.append(4)

...     return l

... 

>>> func(list1)

[1, 2, 3, 4]

格式:函数后面要空一行,最后缩进四格,其他语句,后面不要有隐含的行号

**   //将参数生成字典

>>> def test(**kr):

...     return kr

... 

>>> print test(a=1,b=2,c=4)

{'a': 1, 'c': 4, 'b': 2}

>>> 

*   //将参数整合成元组

>>> def test(*kr):

...     return kr

... 

>>> print test(2,3,4,5,6,[35,56])

(2, 3, 4, 5, 6, [35, 56])

>>> 

*    **  合用

>>> def test(*kr,**z):

...     return kr,z

... 

>>> print test(2,3,4,5,6,[35,56],a=4,b=6,c=9)  如果参数里面有a,b,则传入参数里面不能有a,b

((2, 3, 4, 5, 6, [35, 56]), {'a': 4, 'c': 9, 'b': 6})

>>> 

笔记::

str3="abcdcfghklmn"

str3.center(30)将字符串填充到30个字符

>>> str="dalDSK"

>>> str.swapcase()  交换大小写

'DALdsk'

Python 用下划线作为变量前缀和后缀指定特殊变量

_xxx 不能用’from module import *’导入

__xxx__ 系统定义名字

__xxx 类中的私有变量名

核心风格:避免用下划线作为变量名的开始。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: