Pad*_*ham 3 python dictionary dictionary-comprehension
alphaValueDict = OrderedDict.fromkeys(string.ascii_uppercase,range(0)
i = 1
for k,v in alphaValueDict.iteritems():
alphaValueDict[k] = [i]
i += 1
return alphaValueDict
Run Code Online (Sandbox Code Playgroud)
我需要创建一个有序的dict,其中键是字母中的所有字母,值是1-26。
您可以完全避免对dict的理解:
>>> import string
>>> dict(zip(string.ascii_lowercase, range(1,27)))
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
Run Code Online (Sandbox Code Playgroud)
带有OrderedDict:
>>> import string
>>> from collections import OrderedDict
>>> OrderedDict(zip(string.ascii_lowercase, range(1,27)))
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7), ('h', 8), ('i', 9), ('j', 10), ('k', 11), ('l', 12), ('m', 13), ('n', 14), ('o', 15), ('p', 16), ('q', 17), ('r', 18), ('s', 19), ('t', 20), ('u', 21), ('v', 22), ('w', 23), ('x', 24), ('y', 25), ('z', 26)])
Run Code Online (Sandbox Code Playgroud)
仅当您必须进行更多计算才能获得键/值或增强键/值的可读性时,我才会使用dict-comprehension(极端示例:{noun : age for noun, age in something()}使您了解我们在说什么,而dict(something())在没有的时候)。
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> s= string.ascii_lowercase
>>> from collections import OrderedDict
>>> odict = OrderedDict()
>>> for count,i in enumerate(s):
... odict[count] = i
...
>>> odict
OrderedDict([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p'), (16, 'q'), (17, 'r'), (18, 's'), (19, 't'), (20, 'u'), (21, 'v'), (22, 'w'), (23, 'x'), (24, 'y'), (25, 'z')])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14322 次 |
| 最近记录: |