从嵌套循环中分离结果

时间:2015-07-27 05:17:38

标签: python for-loop dictionary formatting

我创建了一个嵌套循环。

import math 
results = []
for i in range(3,5):
    for j in range(1,5):
        something = (i, ((math.factorial(j-1 + i-1)/ (math.factorial(i-1) * math.factorial(j-1)))))
    print something,

这样的输出如下:(3,1)(3,3)(3,6)(3,10)(4,1)(4,4)(4,10)(4,20) 我怎样才能将两组(3,x)和(4,y)相互分开,然后用两种不同的线条将它们打印出来。所以结果看起来像是:

3:[1,3,6,10]

4:[1,4,10,20]

2 个答案:

答案 0 :(得分:1)

如果您想存储每个i的结果,那么您可以使用collections.defaultdict,示例 -

import math
from collections import defaultdict
results = defaultdict(list)
for i in range(3,5):
    for j in range(1,5):
        results[i].append((math.factorial(j-1 + i-1)/ (math.factorial(i-1) * math.factorial(j-1))))
    print '{} : {}'.format(i,results[i])

结果 -

3 : [1.0, 3.0, 6.0, 10.0]
4 : [1.0, 4.0, 10.0, 20.0]

答案 1 :(得分:1)

您可以使用dict.setdefault()

将其附加到字典值
import math 
results = {}
for i in range(3,5):
    for j in range(1,5):
        something = (i, ((math.factorial(j-1 + i-1)/ (math.factorial(i-1) * math.factorial(j-1)))))
        results.setdefault(something[0], []).append(something[1])  #Create key if not available with default [] value if available get the value and append to the list 
print results

{3: [1, 3, 6, 10], 4: [1, 4, 10, 20]}