我有一个如下所示的数据列表:
// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
Run Code Online (Sandbox Code Playgroud)
......我希望看起来像这样:
0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
Run Code Online (Sandbox Code Playgroud)
我的计划是使用字典,其中t的值是字典的键,而键的值是列表.然后我可以将每个(x,y)附加到列表中.就像是:
# where t = 0, c = (4,7), d = {}
# code 1
d[t].append(c)
Run Code Online (Sandbox Code Playgroud)
现在这会导致IDLE失败.但是,如果我这样做:
# code 2
d[t] = []
d[t].append(c)
Run Code Online (Sandbox Code Playgroud)
......这很有效.
所以问题是:为什么代码2工作,但代码1不工作?
PS我计划做的任何改进都会引起极大的兴趣!我想我必须通过输入检查每个循环上的字典,看看字典键是否已经存在,我想通过使用像max(d.keys())这样的东西:如果它在那里,附加数据,如果没有创建将空列表作为字典值,然后在下一个循环中追加数据.