开发者

Create ranked dict with list comprehension

I have a list [5, 90, 23, 12, 34, 89] etc where every two values should be a (ranked) list in the dictionary.

So the list above would become {1: [5, 90], 2: [23, 12], 3: [34, 89]} etc. I've gotten close with list comprehension but haven't cracked it. I tried:

my_list = [5, 90, 23, 12, 34, 89]
my_dict = dict((i+1, [my_list[i], my_list[i+1]]) for i in xrange(0, len(my_list)/2))

Which works for t开发者_如何学Gohe first key, but all following values are off by one index. How would you do this?


You left a multiple of 2:

dict( (i+1, my_list[2*i : 2*i+2]) for i in xrange(0, len(my_list)/2) )
#                   ^

BTW, you could do this instead (with Python ≥2.6 or Python ≥3.0):

>>> it = iter(my_list)
>>> dict(enumerate(zip(it, it), start=1))
{1: (5, 90), 2: (23, 12), 3: (34, 89)}

(of course, remember to use itertools.izip instead of zip in Python 2.x)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜