Python基础笔记


Python基础笔记

1 入门

1.1 关于整除

3.0以后 "//"为整数除法运算符

eg: 
#3.0以前的情况     
1.0/2.0 = 0.5    1//2 = 0   1/2 =0  
#3.0以后
1/2 = 0.5    1//2 = 0    

1.2 幂运算注意

(-3) ** 2
#=>9

1.3 八进制

010 = 十进制 8

1.4 常用运算函数

1.4.1 pow 幂运算
1.4.2 abs 取绝对值
1.4.3 round 浮点数四舍五入整数
1.4.4 floor 浮点数去除小数部分
32.9
#=>32
int(math.floor(32.9))
#=>32

与floor相对的是ceil函数 注:int(32.9)可以自动取整 上面例子math.floor是多余的

1.4.5 sqrt 计算平方根
1.4.6 str 将值转换成合理形式的字符串
1.4.7 repr 以合法的python表达形式表示值
repr(10000L) 
#=> 10000L
repr("Hello World!")
#=> 'Hello World!'

反引号 `` 代表 repr 3.0后弃用

temp = 42
print "The temp is " + `temp`
#=>The temp is 42

1.5 import 调用函数时省略模块名

from math import sqrt
sqrt(9)
#=> 3.0

1.6 复数 cmath

import cmath
cmath.sqrt(-9) 
#=> 3j

1.7 input与raw_input

input只支持合法的python表达式
raw_input所有输入以字符串形式作为原始数据 尽可能使用raw_input

1.8 长字符串 跨越多行

       使用三个单引号或者三个双引号
''' blablabla
blablabla…'''
注:三引号内的单引号和双引号,可以不用转义符号

1.9 普通字符串忽略代码中的换行符

换行处加上\

" 1 + 2 + \
4 + 5"
#=>"1 + 2 + 4 + 5"

1.10 关于表示路径的转义

r'C:\TestFolder\test.txt'

1.11 Unicode 字符串

u'Hello World!'

在python 3.0以上,所有字符串皆为unicode字符串

2 数据结构

2.1 Sequence

2.1.1 序列包括列表、字符串 、元组
2.1.2 Slice
numbers = [1,2,3,4,5,6,7,8,9,10] #声明

numbers[3,6] 
#=> [4,5,6] 第二个索引号的元素不包含

numbers[-3,]
#=> [8,9,10]

numbers[0:10:2]
 #=> [1,3,5,7,9]

numbers[10:0:-2]
#=> [10,8,6,4,2]

[1,2,3] + [4,5,6]
#=> [1,2,3,4,5,6]

[42] *6
#=> [42,42,42,42,42,42]
2.1.3 空列表

[] 空列表

2.1.4 空元素列表

[None]

2.1.5 in运算符
5 in numbers 
#=> True or False
2.1.6 长度、最大值、最小值

len、max、min

len(numbers)
#=> 10

2.2 list

helloList = list('Hello')  #字符串转换成字符列表
#=>['H','e','l','l','o']
''.join(helloList)  #将字符列表转换成字符串
#=>'Hello'
2.2.1 列表可以修改
numbers[5] = 64
del numbers[5]
分片赋值
name = list('perl')
name[:2] = list('ar')
name
#=> ['p', 'e', 'a', 'r']
name[1:] = list('ython')

#分片插入元素
numbers[5:5] = [6,6]

#分片删除元素
numbers[2:8] = []
2.2.2 列表方法
  • append
    lst= [1,2,3]
    lst.append(4)
    lst
    #=> [1,2,3,4]
    
  • count
    某个元素出现的次数
    [1,5,6,7,53,1,5].count(1)
    #=> 2
    
  • extend
    比lst1=lst1+lst2效率高
    lst1.extend(lst2)
    
  • index
    ['who','where'].index('who')
    #=> 0
    
  • insert
    [1,2,3,4,5].insert(2, 'e')
    #=> [1,2,'e',3,4,5]
    
  • pop
    移除列表中的一个元素(默认最后一个),并返回该元素的值
    x=[1,2,3]
    x.pop()
    #=> 3
    x
    #=> [1,2]     
    

    注:使用pop可以实现数据结构——栈

  • remove
    移除第一个匹配项
    [1,2,3,4,5,6,7,8].remove(5)
    #=> [1,2,3,4,6,7,8]
    
  • reverse
  • sort
    x.sort()#x顺序已改变
    y = sorted(x)#y为x排序后的列表
    

    sort 可选参数(也适用于sorted):
    一、比较函数(见下一节)
    二、key
    x.sort(key=len)
    三、reverse
    x.sort(reverse=True)

  • 自定义排序(比较函数)

    自定义compare(x, y)
    x<y时返回负数,x>y时返回正数,x=y时返回0
    内建cmp函数例子:

    cmp(42, 32)
    #=> 1
    cmp(99, 100)
    #=> -1
    cmp(5,5) 
    #=> 0
    numbers.sort(cmp)
    

2.3 元组

元组不能修改

2.3.1 声明
1,2,3 or (1,2,3)
#=> (1,2,3)
() #空元组
#=> () 
(1,) or 1, 
#=> (1,)
3*(40+2,)
#=>(42,42,42)
2.3.2 tuple函数

传入序列,返回元组

tuple([1,2,3])
#=> (1,2,3)
2.3.3 使用元组的意义

元组可以在映射中当作键使用,列表不行(详见第四章)
元组是很多内建方法的返回值。必须处理他们。

3 字符串

3.1 基本操作

所有标准的序列操作对字符串同样适用,唯一需要记住,字符串是不可变的。

3.2 格式化操作符

字符串 % 元组1

format = "Hello, %s. %s enough for ya?"
values = ('world', 'Hot')
print format % values
#=>Hello, world. Hot enough for ya?

3.3 常用方法

3.3.1 find
x.find("abc")
#=>返回index
3.3.2 join2
seq = ['1','2','3']
sep = '+'
sep.join(seq)
#=> '1+2+3'
3.3.3 lower,upper,title

title功能: 单词首字母大写

3.3.4 replace
x.replace('123', '456')
3.3.5 split是join的逆方法
'/usr/bin/env'.split('/')
#=>['','usr','bin','env']
3.3.6 strip

去除两侧空格,也可传参数,去除指定的头尾字符

3.3.7 translate

同replace 区别在于只处理单个字符。同时进行多个替换。
有时比replace效率高的多。
转换之前,需要完成一张转换表。可用string中的maketrans

maketrans('cs', 'kz')

4 字典 当索引不好用时使用

phonebook={'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
phonebook['Cecil']
#=> '3258'

4.1 dict函数

items = [('name', 'Gumby'), ('age', 42)]
d = dict(items)
d
#=> {'age': 42, 'name': 'Gumby'}

d=dict(name='Gumby', age=42) #另一种声明

4.2 基本字典操作

len(d)
del d[k]
k in d#(检查是否存在k键)

自动添加,对不存在的键复制等于创建了一个新项

4.3 字典的字符串格式化

"Cecil's phone number is %(Cecil)s." % phonebook
#=>"Cecil's phone number is 3258."

4.4 字典方法

4.4.1 clear
x={}
y=x
x['key'] = 'value'
y
#=> {'key': 'value'}

一、x = {} =>y没变
二、x.clear() => y {}

4.4.2 copy & deepcopy
x = {'key1': 'value1', 'key2': 'value2'}
y = x.copy()

一、y.remove('key2')
y和x 均受影响

二、y['key1'] = 'value3'
y受影响,x不受

deepcopy避免了该问题,无论y怎么处理,x都不会变。

4.4.3 fromkeys

使用给定的键建立字典,值默认都为None

dict.fromkeys(['name', 'age'])

也可自己提供值的默认值

dict.fromkeys(['name', 'age'], 'unknown')    
4.4.4 get

更宽松的访问字典项方法

d={}
d['name']
#=> 出错
d.get('name')
#=> None    
4.4.5 has_key
has_key相当于 k in d。python3.0不包含该方法。
4.4.6 items & iteritems

字典项以列表形式返回

d = {'key1': 'value1', 'key2': 'value2'}
d.items()
#=> [('key1', 'value1'), ('key2', 'value2')]
it = d.iteritems()
list(it)
#=> [('key1', 'value1'), ('key2', 'value2')]    
4.4.7 keys & iterkeys

键以列表形式返回

4.4.8 values & itervalues

值以列表形式返回

4.4.9 pop

pop用来获得对应于给定键的值,然后删除该项。

d.pop('key1')
4.4.10 popitem

类似于list.pop
因为字典没有顺序的概念,pop出一个随机项。
用处:若想一个接一个地处理并移除项,用该方法。

4.4.11 setdefault
d.setdefault('name', 'N/A')
#字典中无该键返回如下:
#=> 'N/A'
#字典中有{'name': 'Gumby'}
#=> 'Gumby'
4.4.12 update

利用一个字典项更新另外一个字典

d.update(x) #更新源d

5 条件、循环和其他语句

5.1 more about print

5.1.1 logging模块比print更适合记录日志
5.1.2 使用逗号打印多个表达式
print 'Age', 42, '?'

5.2 more about import

import somemodule
#or
from somemodule import somefunction1, somefunction2
#or 
from somemodule import *

import somemodule as alias
#=>alias.somefunction()

from somemodule import somefunction as aliasfunction
#=>aliasfunction()

5.3 赋值语句

5.3.1 多个赋值
x, y, z = 1, 2, 3
5.3.2 交换变量
x, y = y, x
5.3.3 以上发生了序列解包(sequence unpacking)
values = 1, 2, 3
values
#=> (1, 2, 3)
x, y, z = values
x
#=> 1    

常用于函数方法返回元组时

key, value = scoundrel.popitem()    

python 3.0 特殊解包

a, b, rest* = [1, 2, 3, 4]
rest
#=> [3, 4]    
5.3.4 链式赋值
x = y = somefunction()
#等同于
y = somefunction()
x = y
#不一定等价于
x = somefunction()
y = somefunction()    
5.3.5 增量赋值

与其他语言差不多+=、*=等

5.3.6 if语句

         如下会被视为False:
False None 0 "" () [] {}
其他非空值被视为True

True == 1 => True
False == 0 => True
  • bool函数
    bool('test')
    #=> True
    bool(42)
    #=> True
    bool('')
    #=> False
    
  • if 语句写法
    if true:
    .....
    if 条件1 and 条件2:
    and, or, not     
    
  • 更多比较运算符
    x is y  #x、y是同一个对象
    x is not y
    x in y
    x not in y
    

    注:0<age<100 的形式也是可以的

    #字符串可以根据字母顺序进行比较
    "a"<"b" => True  
    [1,2] < [2,1] #比较第一个值
    [2, [1, 4]] < [2, [1, 5]]   
    
  • 断言
    用法说明:
    like:
    if not condition:
        crash program
    
    age = -1
    assert 0<age<100, 'message' #or assert 0<age<100
    #=>breakdown     
    
  • while 循环
    x=1
    while x<=100:
        print x
        x += 1     
    
  • for 循环
    for number in range(1, 100)
        print number   
    

    range包含下限1,不包含上限1003

    #循环遍历字典
    for key in d:
        print key, d[key]     
    
  • 迭代工具
    itertools模块、python内建模块两处包含迭代工具
    • 并行迭代(zip函数)
      names = ['name1', 'name2']
      ages = [12, 45]
      zip(names, ages)
      #=> [('name1', 12), ('name2', 45)]
      
      #解包元组,遍历
      for name, age in zip(names, ages):
          print name, 'is', age, 'years old'     
      
    • 编号迭代(enumerate)
      enumerate函数可以在提供索引的地方迭代索引-值对
      for index, string in enumerate(strings):
          if 'xxx' in string:
          strings[index] = '[censored]'      
      
    • 翻转和排序迭代(reversed, sorted)

      reversed, sorted与序列方法reverse, sort差不多,区别在于reverse和sort改变原调用对象
      sorted函数返回列表
      reversed函数返回一个可迭代对象

      list(reversed('Hello,World!'))
      #=>'!dlroW,olleH'
      
    • for…else
      for n in range(99, 81, -1):
          root = sqrt(n)
          if root == int(root):
              print n
              break
      else:
          print "Didn't find it!"      
      

      break直接进入else语句块

    • 轻量级循环 列表推导式
      [x*x for x in range(10)]
      #=> [0, 1, 4, 9, 25, 36, 49, 64, 81]      
      
      #可加条件:
      [x*x for x in range(10) if x % 3 ==0]
      #=>[0, 9, 36, 81]
      
      [(x, y) for x in range(3) for y in range(3)]
      #=>[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
      
      #等同于
      result = []
      for x in range(3):
          for y in range(3):
          result.append((x, y))
      
    • pass、del和exec

      pass 程序什么事情都不做 用作预留占位符
      python空代码块是非法的。需要如下做:

      if x==0:
          pass
      
      x=1
      y=x
      x=None
      y => 1
      y=None
      #1就漂在内存里了,python垃圾回收器会去处理它
      

      另外的办法是del

      x=1
      del x
      x
      #=>报错,del不但删除内容,也删除变量名
      x=1
      y=x
      del x
      y
      #=>1 原因:该情况del只删除了名称      
      

      exec执行字符串中的python语句(风险极大,慎重,并且是很严重的安全漏洞)

      exec "print 'Hello,world!'"     
      

      字符串代码,单独一个命名空间

      scope={}
      exec 'sqrt = 1' in scope
      scope['sqrt']
      #=>1
      len(scope)
      #=>2
      scope.keys()
      #=> ['sqrt', '__builtins__']      
      

      eval会计算python表达式(字符串形式书写),返回结果值

      eval(raw_input("Enter an arithmetic expression: "))      
      

      eval同样也可使用命名空间

      scope = {}
      scope['x'] = 2
      scope['y'] = 3
      eval('x * y', scope)
      #=>6      
      
    • chr(n) & ord(c)
      chr(number)
      #=> 对应的字符串
      number 0~256
      ord(char)
      #=> number      
      

6 抽象(函数)

6.1 斐波那契数列

fibs = [0, 1]
for i in range(8):
    fibs.append(fibs[-2] + fibs[-1])
fibs
#=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#抽象成
fibs(num)   

6.2 创建函数

   def fibs(num):
       'generate fib sequence'
       result = [0, 1]
v       for i in range(num-2):
           result.append(result[-2] + result[-1])
       return result   

Emacs提供的访问函数说明的方法4
函数如果无返回值,返回None

6.3 参数

6.3.1 基本

函数内改变参数变量的值,不会改变外部传入变量的值。即值传递参数
可变的数据结构,如列表。引用传递。

6.3.2 不可变的数据结构,无法像C++方式的引用/指针参数,不可改变参数

用返回值:

def inc(x): return x+1    

小技巧:

def inc([x]): x[0] = x[0] + 1
foo = [10]
inc(foo)
foo 
#=> 11
6.3.3 参数顺序问题
def hello(greeting, name):
    print '%s, %s' % (greeting, name)

hello(greeting='Hello', name='world')

def hello2(greeting='Hello', name='world') #提供默认值
6.3.4 多参数
  • def print_params(title, *params):
    使用"*"将所有值放置在同一元组内
    print_params('Print params', 'param1', 'param2')
    #=>Print params
    #=>('param1', 'param2')
    
    print_params('Nothing')
    #=>Nothing
    #=>()    
    

    v**** def print_params2(**params):

    print_params2(x=1, y=2, z=3)
    #=>( 'x' : 1, 'y' : 2, 'z' : 3)     
    
  • def print_params3(x, y, z=3, pospar, keypar):
    print_param3(1,2,3,4,5,6,foo=1,bar=2)
    #=>1,2,3
    #=>(4,5,6)
    #=>{'foo':1,'bar':2}
    print_param3(1,2)
    #=>1,2,3
    #=>()
    #=>{}
    
6.3.5 多元素元组直接做参数
#序列用法
def  add(x+y): return x + y
params = (1, 2)
add(*params)
#=>3
#字典用法
params = {'name': 'Sir Robin', 'greeting': 'Well met'}
hello3(**params)
#=>Well met, Sir Robin!
  • 序列,** 字典
6.3.6 内建变量名和值的字典
scope = vars()#vars()返回全局变量的字典
x=1
scope['x']
#=>1
scope['x'] += 1
x
#=>2

即作用域的概念5

6.3.7 函数内访问全局变量

在函数作用域内调用同名全局变量,需使用globals()['globalName']

def combine(param):
    print param + globals()['param']
param = 'berry'
combine('Shrub')
#=>Shrubberry
6.3.8 函数内改变全局变量
x=1
def change_global():
    global x
    x = x + 1
change_global()
x
#=>2
6.3.9 递归
def power(x, n):
    if n == 0:
    return 1
    else:
    return x * power(x, n-1)
6.3.10 函数式编程常用函数
  • map

    map(func, seq [, seq, …])
    对序列中的每个元素应用函数
    [return1, return2, return3]

  • filter
    filter(func, seq)n func需返回布尔值
  • reduce
    reduce(func, seq[, initial])
    等同于func(func(func(seq[0], seq[1]), seq[2])...)
    

7 更加抽象(面向对象)

Footnotes:

1 要在格式化字符串中输入"%",则需要输入"%%"

2 最常用例子:'\\'.join(dirs)

3 range(1,100)实际是1~99

4 fibs.__doc__ 可访问函数说明、help(fibs) 更好用

5 函数调用会创建一个作用域

Last Updated 2013-02-16 13:43:16 中国标准时间

Author: ChrisChen(ChrisChen3121@gmail.com)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值