3

So I am very new to python and I cant for the life of me figure out why these two statements evaluate differently,

[3*x for x in range(1,11) if x > 5]

[18, 21, 24, 27, 30]

{3*x for x in range(1,11) if x > 5}

set([24, 18, 27, 21, 30])

The top one makes perfect sense to me but why does the second print things in such a weird order? I know that hard brackets '[' are for lists and '{' for dictionaries.

4

2 回答 2

12

第二个不是字典而是集合。集合和字典都是无序的。元素不会以任何特定的有意义的顺序存储或显示。

于 2013-03-05T05:06:51.150 回答
0

对于字典,您必须分配键、值对,例如 {key:value}

所以你的问题的答案如下,

{3*x:3*x for x in range(1,11) if x > 5}

输出如下所示,

{18:18、21:21、24:24、27:27、30:30}

于 2013-03-11T06:57:25.973 回答