1
Muninn 2014-05-14 23:34:35 +08:00
不太理解
|
3
zedde OP 1-20 类似{1:{2:3, 4:5}, 6:{7:8, 9:10}, 11:{12:13, 14:15}, 16:{17:18, 19:20}}
|
4
fdsfsdfsdf3334 2014-05-15 00:06:58 +08:00
# coding=utf-8
t={} #初始化字典 for x in range(1,21): if x%5==1: print x t[x]="{"+str(x+1)+":"+str(x+2)+","+str(x+3)+":"+str(x+4)+"}" t1= sorted(t.iteritems(), key=lambda d:d[0], reverse = False) #按照键值排序 print t1 |
5
fdsfsdfsdf3334 2014-05-15 00:07:38 +08:00
|
6
fdsfsdfsdf3334 2014-05-15 00:09:27 +08:00
好像有点问题,你看看能不能用
|
7
fdsfsdfsdf3334 2014-05-15 00:14:12 +08:00
print "---------------------------------------------\n\r"
print "t:\n\r" print t print t[1] print "---------------------------------------------\n\r" print "t1:\n\r" print t1 print t1[0][1] |
8
kxxoling 2014-05-15 00:44:25 +08:00
我理解你是想通过一个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 ``` |
9
delo 2014-05-15 00:44:43 +08:00
|
10
kxxoling 2014-05-15 00:45:56 +08:00
额,v2ex不支持这么加代码。。。不过逻辑不复杂,我就不用gist了,讲究看看吧~
|
11
palytoxin 2014-05-15 00:51:17 +08:00 via iPhone
这不是和女神合租的rubyer么,没认错吧
|
12
cbsw 2014-05-15 01:02:05 +08:00
一行代码而已
{k:{k+1:k+2, k+3:k+4} for k in [5*i+1 for i in range(4)]} 如果要写成函数,就把最后一个 4 作为参数 |
13
kavinyao 2014-05-15 04:31:20 +08:00 1
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}} |
14
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 |
15
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 ``` |
16
wangyongbo 2014-05-15 10:52:41 +08:00 2
{ x : { x + 1 :x+ 2, x+ 3: x+ 4} for x in range(1, 20, 5)}
|
17
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)}
|
18
toctan 2014-05-15 13:00:32 +08:00
Ruby:
(1..20).step(5).reduce({}) { |r, x| r.merge(x => Hash[*(x + 1..x + 4)]) } or the lazy way: Hash.new { |h, k| h[k] = Hash[*(k + 1..k + 4)]) } |
19
hanks315 2014-05-15 13:57:40 +08:00
|
20
foomorrow 2014-05-15 16:14:46 +08:00
n = 2
dict(map(lambda x:(x,dict(((x+1,x+2),(x+3,x+4)))),[x+1 for x in xrange(0,n*10,5)])) |