之前自己也遇到過一次,這段時(shí)間在群里也遇到過幾次的一個(gè)問題
用python2.7寫的一段程序,里面用到了字典推導(dǎo)式,但是服務(wù)器版本是python2.6,無法運(yùn)行。
今天查了下關(guān)于Dict Comprehensions,在pep274中有明確的說明。
http://legacy.python.org/dev/peps/pep-0274/
Implementation
All implementation details were resolved in the Python 2.7 and 3.0
time-frame.
這個(gè)是從2.7之后才加上的。
2.6版本中我們怎么用呢,其實(shí)用一個(gè)for循環(huán)來解決就好了
#表達(dá)式寫法
In [4]: print {i : chr(65+i) for i in range(4)}
{0: 'A', 1: 'B', 2: 'C', 3: 'D'}
#for循環(huán)寫法
In [5]: d = {}
In [6]: for i in range(4):
...: d[i] = chr(65+i)
...:
In [7]: print d
{0: 'A', 1: 'B', 2: 'C', 3: 'D'}