最近换用Python3, 发现使用是有许多与Python2.6不一致的地方。
https://wiki.python.org/moin/Python2orPython3
Python3 又称Python3k,Python 3000,是Python家族中第一个不向后兼容的发布版本。
简要总结:
A函数更新:
1.Print 变为函数调用,必须使用print()
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
print("There are <", 2**32, "> possibilities!", sep="")
>>>There are <4294967296> possibilities!
2. 许多地方用Views | Iterators 替换 Lists (E.g.返回值)
2.1 dict function return view
dict.keys()
dict.items()
dict.values()
Old: k=d.keys(); k.sort();
New: k=sorted(d);
nouser dict.iterkeys(), dict.iteritems,dict.itervalues
2.2 map() and filter() return iterators
#注意Iterator的用处,转回list在遍历时刻不是好方案(O(n)->O(N^2))
Old: mylist=map(xxx)
New : mylist=list(map(xxx))
#map截断
Old:map(func, *sequences)
New:list(map(func, itertools.zip_longest(*sequences))).
2.3 rang() -> xrang()
2.4 zip() return iterators
3.排序比较
3.1 (<, <=, >=, >) raise a TypeError exception, 类型错不再返回false (== ,!= 仍然可以接受不同类型)
3.2 builtin.sorted() and list.sorted() 只有key参数
3.3 取消cmp()函数,内部函数用__it__(), __eg__(),替代。 使用 (a>b)-(a<b)替代 cmp(a,b)
Old: cmp(a,b)
New: (a>b)-(b<a)
#待续
###############################################
x.x 引用库'.'语法
目录:
|---main.py
|---lib
| |---b.py
| |---a.py
| |---__init__.py
|---__init__.py
#main.py
from lib.b import fx
fx()
#a.py
def f():
print ('a.f() is call')
#b.py
from .a import f
def fx():
print('b.f() is called')
f()
注意b调用了a中的函数, 这里 from .a import f
在lib文件夹外部调用文件内部函数,如果内部有依赖需要用"."表示相对路径
>>>python main.py
>>>a.f() is call
>>>b.f() is called
但是如果使用了了“.”,直接在文件夹内部调用就不行
python b.py
Traceback (most recent call last):
File "b.py", line 6, in <module>
from .a import f
SystemError: Parent module '' not loaded, cannot perform relative import
要想直接调用b.py 需要这么调用:
#cd到python 父目录
python -m lib.b
a.f() is call
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
如果不使用. 那么在lib目录里可以直接运行python b.py
注意一下区别吧。
good luck
hack
find . -print 2>/dev/null|awk '!/\.$/ {for (i=1;i<NF;i++){d=length($i);if ( d < 5 && i != 1 )d=5;printf("%"d"s","|")}print "---"$NF}' FS='/'