Storing and updating lists in Python dictionaries: why does this happen?

前端 未结 4 1579
一向
一向 2021-01-30 22:19

I have a list of data that looks like the following:

// 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

... and

4条回答
  •  [愿得一人]
    2021-01-30 23:18

    I think you want to use setdefault. It's a bit weird to use but does exactly what you need.

    d.setdefault(t, []).append(c)
    

    The .setdefault method will return the element (in our case, a list) that's bound to the dict's key t if that key exists. If it doesn't, it will bind an empty list to the key t and return it. So either way, a list will be there that the .append method can then append the tuple c to.

提交回复
热议问题