打印字典列表步进3乘3

时间:2014-10-29 16:06:10

标签: python

我必须创建一个列表的字典理解,如下所示:

  

[{0:[1,2,3]},{1:[2,3,4}},{2:[3,4,5]} ...... {100:[101,102,   103]}]

使用以下代码创建:

  

a = [{I-1:范围(I,i + 3),范围内的I(1,101)]

现在我被卡住了打印3到3的列表中的每个元素,即:

        {0: [1, 2, 3]}
        {3: [4, 5, 6]}
        {6: [7, 8, 9]}
        …
        {99: [100, 101, 102]}

1 个答案:

答案 0 :(得分:3)

你应该可以使用简单的切片:

a[::3]

将为您提供每个第3个字典的清单。只需将其放入循环中即可打印出来:

for dct in a[::3]:
    print(dct)

演示:

>>> a=[{I-1:range(I,I+3)} for I in range(1,101)]
>>> for dct in a[::3]:
...   print(dct)
... 
{0: [1, 2, 3]}
{3: [4, 5, 6]}
{6: [7, 8, 9]}
{9: [10, 11, 12]}
{12: [13, 14, 15]}
{15: [16, 17, 18]}
{18: [19, 20, 21]}
{21: [22, 23, 24]}
{24: [25, 26, 27]}
{27: [28, 29, 30]}
{30: [31, 32, 33]}
{33: [34, 35, 36]}
{36: [37, 38, 39]}
{39: [40, 41, 42]}
{42: [43, 44, 45]}
{45: [46, 47, 48]}
{48: [49, 50, 51]}
{51: [52, 53, 54]}
{54: [55, 56, 57]}
{57: [58, 59, 60]}
{60: [61, 62, 63]}
{63: [64, 65, 66]}
{66: [67, 68, 69]}
{69: [70, 71, 72]}
{72: [73, 74, 75]}
{75: [76, 77, 78]}
{78: [79, 80, 81]}
{81: [82, 83, 84]}
{84: [85, 86, 87]}
{87: [88, 89, 90]}
{90: [91, 92, 93]}
{93: [94, 95, 96]}
{96: [97, 98, 99]}
{99: [100, 101, 102]}