星期六, 二月 10, 2007

python map [] to empty strings

>>> L1 = ['a', 'b', 'c']
>>> L2 = [1, 2, 3]
>>> zip(L1, L2)
[('a', 1), ('b', 2), ('c', 3)]
>>> map(L1, L2)
Traceback (most recent call last):
File "", line 1, in ?
TypeError: 'list' object is not callable

>>> map(None, L1, L2)
[('a', 1), ('b', 2), ('c', 3)]
>>> dict(zip(L1, L2))
{'a': 1, 'c': 3, 'b': 2}
>>> dict(map(None, L1, L2))
{'a': 1, 'c': 3, 'b': 2}

>>> L3 = []
>>> zip(L1, L3)
[]
>>> map(L1, L3)
[]
>>> map(None, L1, L3)
[('a', None), ('b', None), ('c', None)]
>>> dict(zip(L1, L3))
{}
>>> dict(map(None, L1, L3))
{'a': None, 'c': None, 'b': None}

>>> def fun(A, B):
... if B == None: B = ''
... return A, B
...
map(fun, L1, L2)
[('a', 1), ('b', 2), ('c', 3)
>>> map(fun, L1, L3)
[('a', ''), ('b', ''), ('c', '')]
>>> dict(map(fun, L1, L3))
{'a': '', 'c': '', 'b': ''}

没有评论: