`
fangzhouxing
  • 浏览: 211469 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Python/Django学习笔记(3):用一周时间学习Python语言

阅读更多

      用了一周时间学习Python语言,把《Learning Python(第3版,2007.10)》这本书的内容基本上比较仔细地看了一遍。本文摘录一些有趣的语言特性。

 

1. ==和is操作符

 

    来自: 第4章:Introducing Python Object Types

    例子1:

	L = [1, 2, 3]
	M = [1, 2, 3]
	L == M  <-- true
	L is M  <-- false

     例子2:

L = [1, 2, 3]
M = L                # M and L reference the same object
L == M    <-- 分别指向的对象是否相同?true
L is M  <-- 是否指向同一个对象?true
 

2. 字符串加前缀字母

 

    来自: 第4章:Introducing Python Object Types

     例子1:

	myfile = open(r'C:\new\text.dat', 'w')
	 相当于:
        myfile = open('C:\\new\\text.dat', 'w')

     例子2:u表示中文字符

 

#coding=utf-8

menuDefinitions = [{
        "title" : u'编程示范',
        "cls" : 'active',
    。。。

 

3.slicing(片段)的概念 

 

      来自: 第4章:Introducing Python Object Types

	str = "media/client/menuitem/Namespace.js"
	str[-12:]=="Namespace.js"
	str[:-12]=="media/client/menuitem/"
 

4.通过例子学习List Comprehensions

    来自:第4章:Introducing Python Object Types

squares = [x ** 2 for x in [1, 2, 3, 4, 5]]  <------ List Comprehensions

与下面的for等价:
squares = []
for x in [1, 2, 3, 4, 5]:
    squares.append(x ** 2)

 

5.用缩进来标识代码块

    来自:第10章:Introducing Python Statements

    这是最令人吃惊的语言特性!

格式:
    Header line:
        Nested statement block  

 

6.只要用一条语句就能交换两个变量的值

    来自:第11章 Assignment, Expressions, and print

nudge = 1
wink = 2
nudge, wink = wink, nudge   <----- Tuple assignment

 

7.If 测试

    来自:第12章 if Tests

    例子1:

branch = {'spam': 1.25,
      'ham': 1.99,
      'eggs': 0.99}

print branch.get('spam', 'Bad choice') <--- 代替了if

     例子2:

   -- A = Y if X else Z
      也可以写为: A = [Z, Y][bool(X)]

 

8. 循环

    来自:第13章 while and for Loops

    例子1:

while x:
    if match(x[0]):
	print 'Ni'
        break            # Exit, go around else <--- 跳过 else:
    x = x[1:]
else:                             <----- while 循环正常结束时执行 else:
    print 'Not found'
 

    例子2:按行读文件内容

for line in open('test.txt'):
    print line
 

9. 用单元测试来保证软件的质量显得更加重要

    来自:第15章 Function Basics

摘录: 写道

Of course, this polymorphic model of programming means we have to test our code
to detect errors, rather than providing type declarations a compiler can use to detect
some types of errors for us ahead of time. In exchange for an initial bit of testing,
though, we radically reduce the amount of code we have to write, and radically
increase our code’s flexibility.

 

10.关于lambda的例子

    来自:第17章 Advanced Function Topics

	f = lambda x, y, z: x + y + z   <---- lambda = Anonymous Functions
	等同于
	def func(x, y, z): return x + y + z  

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics