我理解你是想通过一个list获取这样的dict,list的长度要能被5整除。 ``` l = range(1, 21) assert len(l)%5 == 0 d = {} for i in range(0, len(l), 5): d[l[i]] = {l[i+1]: l[i+2], l[i+3]: l[i+4]} print d ```
一行代码而已 {k:{k+1:k+2, k+3:k+4} for k in [5*i+1 for i in range(4)]} 如果要写成函数,就把最后一个 4 作为参数
kavinyao
2014-05-15 04:31:20 +08:00
In [13]: {i: {j:j+1 for j in [i+1, i+3]} for i in range(1, 20, 5)} Out[13]: {1: {2: 3, 4: 5}, 6: {7: 8, 9: 10}, 11: {12: 13, 14: 15}, 16: {17: 18, 19: 20}}
daniel7725
2014-05-15 09:30:27 +08:00
``` def test(num): if num <5: return None targe = {} for i in xrange(1,num,5): tmp_dict = {str(i):{str(i+1):str(i+2),str(i+3):str(i+4)}} targe.update(tmp_dict) return targe
daniel7725
2014-05-15 09:34:51 +08:00
看看v2ex支不支持markdown ``` def test(num): if num <5: return None targe = {} for i in xrange(1,num,5): tmp_dict = {str(i):{str(i+1):str(i+2),str(i+3):str(i+4)}} targe.update(tmp_dict) return targe ```
wangyongbo
2014-05-15 10:52:41 +08:00
{ x : { x + 1 :x+ 2, x+ 3: x+ 4} for x in range(1, 20, 5)}
wangyongbo
2014-05-15 10:54:08 +08:00
{ x : { i : i + 1 for i in xrange(x+1, x+4, 2)} for x in range(1, 20, 5)}