开发者

Is there a better way to assign a default value for next()

url_params = {}
for i in t:
    try:
        url_params[i] = t.next()
    except:
        url_params[i] = None

Because this just开发者_运维知识库 looks silly to me. I'm converting a list to a dict by pairing up neighboring elements. There are cases, however, where I won't always have a pair. The tailing element is still important but it's value isn't important.


This is more easily done like this:

from itertools import izip_longest
url_params = dict(izip_longest(*[iter(t)] * 2))

Example: For t = range(11), this produces

{0: 1, 2: 3, 4: 5, 6: 7, 8: 9, 10: None}


Also works:

>>> dict(zip(t[::2], t[1::2]+[None]))
{0: 1, 2: 3, 4: 5, 6: 7, 8: 9, 10: None}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜