前段时间在码农周刊上看到了一个不错的学习Python的网站(Code Cademy),不是枯燥的说教,而是类似于游戏世界中的任务系统,一个一个的去完成。一做起来就发现根本停不下来,历经10多个小时终于全部完成了,也相应的做了一些笔记。过段时间准备再做一遍,更新下笔记,并加深了解。
name = raw_input(\"What is your name\")
这句会在console要求用户输入string,作为name的值。
逻辑运算符顺序:not>and>or
dir(xx)
: sets xx to a list of things
list
a = []
a.insert(1,\"dog\") # 按顺序插入,原有顺序会依次后移
a.remove(xx)
dict
1) del dic_name[\'key\']
2) loop:
d = {\"foo\" : \"bar\"}
for key in d:
print d[key]
3) another way to find key: print d.items()
print [\”O\”]*5 : [\’O\’, \’O\’, \’O\’, \’O\’, \’O\’]
join操作符:
letters = [\'a\', \'b\', \'c\', \'d\']
print \"---\".join(letters)
输出为a---b---c---d
while/else, for/else
只要循环正常退出(没有碰到break什么的),else就会被执行。
print 和 逗号
word = \"Marble\"
for char in word:
print char,
这里“,”保证了输出都在同一行
for循环中的index
choices = [\'pizza\', \'pasta\', \'salad\', \'nachos\']
print \'Your choices are: \'
for index, item in enumerate(choices):
print index, item
enumerate可以帮我们为被循环对象创建index
zip能创建2个以上lists的pair,在最短的list的end处停止。
善用逗号
a, b, c = 1, 2, 3
a, b, c = string.split(\':\')
善用逗号2print a, b
优于 print a + \" \" + b
,因为后者使用了字符串连接符,可能会碰到类型不匹配的问题。
List分片
活用步长的-1:
lists = [1,2,3,4,5];
print lists[::-1]
输出结果:[5,4,3,2,1]
filter 和 lambda
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
会把符合条件的值给留下,剩下的丢弃。打印出[0, 3, 6, 9, 12, 15]
bit operation
1) print 0b111
#7, 用二进制表示10进制数
2) bin()
函数,返回二进制数的string形式;类似的,oct()
,hex()
分别返回八进制和十六进制数的string。
3) int(\"111\",2)
,返回2进制111的10进制数。
类的继承和重载
1) 可以在子类里直接定义和父类同名的方法,就自动重载了。
2) 如果子类已经定义了和父类同名的方法,可以直接使用super
来调用父类的方法,例如
class Derived(Base):
def m(self):
return super(Derived, self).m()
File I/O
1) f = open(\"a.txt\", \"w\")
: 这里w为write-only mode,还可以是r (read-only mode) 和 r+ (read and write mode),a (append mode)
2) 写文件语法 f.write(something)
。这里注意something一定要为string类型,可以用str()强制转换。不然会写入报错。
3) 读全文件非常简单,直接f.read()
就好。
4) 如果要按行读文件,直接f.readline()
会读取第一行,再调用一次会读取第二行,以此类推。
5) 读或写完文件后,一定要记得f.close()
。
6) 自动close file:
with open(\"text.txt\", \"w\") as textfile:
textfile.write(\"Success!\")
with
和as
里有内嵌的方法__enter__()
和__exit__()
,会自动帮我们close file。
7) 检查文件有没有被关闭,f.closed
。
List Comprehensions
Python支持便捷的完成List的表达式,例如原代码:
list_origin = [1, 2, 3, 4, 5, 6]
list_new = []
for i in list_origin:
if i % 2 == 0:
list_new.append(i)
可以直接一行搞定:
list_origin = [1, 2, 3, 4, 5, 6]
list_new = [i for i in list_origin if i % 2 == 0]