Python基础(1)

  0、Python中一切皆对象。

  1、内置数据类型

  type()可以用来检查类型,如type(a_list)

  1)列表list

a_list = [1, 2, 3, 4, 5]
a_list                            # [1, 2, 3, 4, 5]
a_list[3]                         # 4。a_list[-1]结果为5
a_list[1 : 3]                     # [2, 3],切片
a_list.extend([6, 7, 8])          # 增加元素

  2)元组tuple:不可变的列表

a_tuple = (1, 2, 3, 4, 5)
a_tuple[3]

  3)集合set:无序,元素不重复

a_set = set([1, 2, 44, 3])  
a_set.add(5)                 # 结果a_set为set([1, 2, 3, 44, 5])
len(a_set)                   # 求元素个数
a_set.update([7, 9])         # 增加多个元素
a_set.discard(5)             # 删除元素
30 in a_set                  # 判断元素是否在set中
b_set = set([44, 55])
a_set.union(b_set)           # set的集合操作

  4)字典dictionary:无序的键值对集合,”键“不可重复

a_dict = {'a': 1, 'b': 2, 'c': 3}
# 字典是”关联数组“,所以使用[key]读写value
a_dict['a']
1
# 迭代
for key in a_dict:
    print a_dict[key]    # 输出:
1
3
2

  5)字符串

  (1)函数/方法

# join():使用分隔符将一个可迭代类型(如列表、元组等)的各个string元素连接起来
a_list = ['My', 'name', 'is', 'hanerfan']
' '.join(a_list)    # 输出:
'My name is hanerfan'

# split():将一个string按照指定分隔符拆分成多个string并存放到一个list中
str = 'My name is hanerfan'
str.split(' ')    # 输出:
['My', 'name', 'is', 'hanerfan']

 

  2、函数/方法

  1)可变参数

# 将传入的参数以元组形式存放到args中
def test(*args):
    print args
args = (1, 2, 3)
test(args)
# 输出: ((1, 2, 3),) test(1, 2, 3) # 输出: (1, 2, 3) # 若实参使用*,则把实参(元组、列表等)的元素存放到test的args中 test(*args) # 输出: (1, 2, 3) test(*[1, 2, 3]) # 输出: (1, 2, 3)
# 将传入的参数以字典形式存放到args中
def test(**args):
    print args
args = {'a' : 1, 'b' : 2, 'c' : 3}
test(a
= 1, b = 2, c = 3) # 输出: {'a': 1, 'c': 3, 'b': 2} # 若实参使用**,则把实参(字典)的元素存放到test的args中 test(**args) # 输出: {'a': 1, 'c': 3, 'b': 2}

 

  3,闭合(闭包):

  Python中使用闭包主要是在进行函数式开发时使用。如果内部函数对外部作用域(但不是全局作用域)的变量进行引用,该内部函数就被认为是闭包(closure)。如下例:

>>> def addx(x):
...     def addxy(y) : return x  + y
...     return addxy
... 
>>> f = addx(10)
>>> type(f)
<type 'function'>
>>> f
<function addxy at 0x2b5a3b186cf8> >>> f(8) 18

  使用闭包时要注意的问题:

  1)闭包中不能“直接”修改外部作用域的局部变量;

  2)在一个作用域内为某个变量赋值时,该变量就变成该域内的局部变量(同时覆盖外部作用域的同名变量)。
所以如下方式使用闭包是错误的:

>>> def foo():
...     x = 10
...     def bar():
...         x += 1
...         return x
...     return bar
... 
>>> f = foo()
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in bar
UnboundLocalError: local variable 'x' referenced before assignment

  可以使用以下的方式修正这个错误:

  (1)把x声明为global,以访问(包括修改)外部作用域的变量:

>>> x = 10
>>> def foobar():
...     global x
...     print x
...     x += 1
...     print x
... 
>>> foobar()
10
11
>>> print x
11

  (2)把x声明为nonlocal的(Python3的新特性):

>>> def foo():
...    x = 10
...    def bar():
...        nonlocal x
...        print(x)
...        x += 1
...    bar()
...    print(x)
>>> foo()
10
11

  (3)使用容器:

>>> def foo():
...     a = [1] 
...     def bar():
...         a[0] += 1
...         print a
...     bar()
...     print a
... 
>>> foo()
[2]
[2]

  闭包还有类似于配置文件的作用,详见下例:

>>> def make_filter(keep):
...     def the_filter(file_name):
...         file = open(file_name)
...         lines = file.readlines()
...         file.close()
...         filter_doc = [i for i in lines if keep in i]     # 结果存储到列表中
...         return filter_doc
...     return the_filter
... 
>>> 
>>> filter = make_filter("pass")        # 取出result.txt中含pass的行
>>> filter_result = filter("result.txt")
>>> filter_result
['passby er\n', 'passenger hi\n']

 

  4,生成器(Generator):一种创建迭代器的简单有力的工具。它的形式和普通函数类似,只是在返回的地方使用了yield语句。例子:

>>> def reverse(data):
...     for index in range(len(data) - 1, -1, -1):
...         yield data[index]
... 
>>> for char in reverse('golf'):
...     print char
... 
f
l
o
g
>>> def fib(max):
...     a, b = 0, 1
...     while a < max:
...         yield a
...         a, b = b, a + b
... 
>>> for n in fib(4): 
...     print n
... 
0
1
1
2
3

  其实生成器能做的事情,(基于类的)迭代器也能做。但生成器相对紧凑,因为它的__iter__()和__next__()是自动创建的。另外两个特征是:(函数的)局部变量和执行状态在多次调用之间是自动保存的;当生成器终止时,它会自动触发StopIteration异常。因此,生成器是一种和普通函数无异但却更容易创建迭代器的方法。

 

  参考资料:

  http://woodpecker.org.cn/diveintopython3/index.html

  https://docs.python.org/2/tutorial/classes.html#generators

  http://blog.csdn.net/marty_fu/article/details/7679297

 

 

不断学习中。。。

posted on 2014-04-19 01:47  han'er  阅读(212)  评论(0编辑  收藏  举报

导航