在Python字典中存储和更新列表:为什么会发生这种情况? [英] Storing and updating lists in Python dictionaries: why does this happen?

查看:144
本文介绍了在Python字典中存储和更新列表:为什么会发生这种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据列表,如下所示:

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

...我想让它看起来像:

  0,(4,7),(2,7),(9, 5),(6,7)
1,(2,5),(4,7),(9,0),(6.8)

我的计划是使用一个字典,其中t的值是字典的关键字,而对该键的值将是一个列表。我可以将每个(x,y)附加到列表中。如下:

 #其中t = 0,c =(4,7),d = {} 

#代码1
d [t] .append(c)

IDLE失败。但是,如果我这样做:

 #code 2 
d [t] = []
d [t] .append(c)

...这个工作。



所以问题是:为什么代码2工作,但代码1不?



PS Any改善我正在计划做什么会是非常有意思的!我想我必须通过输入检查每个循环上的字典,看看字典键是否已经存在,我想通过使用像max(d.keys())的东西:如果它在那里,请附加数据,如果不创建空列表作为字典值,然后在下一个循环中附加数据。

解决方案

我们来看看

  d [t] .append(c)

D [t]的?尝试一下。

  d = {} 
t = 0
d [t]

你有什么?哦。 d 中没有任何密钥 t



现在尝试这个。

  d [t] = [] 
d [t]

啊现在在 d 中有一些 t



<你可以做几件事情。


  1. 使用示例2。

  2. 使用 setdefault d.setdefault(t,[])。append(c)

  3. 使用 collections.defaultdict 。您将使用 defaultdict(list)而不是一个简单的字典, {}






编辑1.优化



从上述形式的文件中给出输入行:ts,x,y,分组过程是不必要的。没有理由从(ts,x,y)到一个更复杂的
列表(ts,(x,y),(x,y),(x,y) 。)。原始列表可以按照到达的方式进行处理。

  d = collections.defaultdict(list)
for ts, x,y in someFileOrListOrQueryOrWhatever:
d [ts] .append((x,y))






编辑2.答案问题



在初始化字典时,需要告诉字典什么键值数据结构将是什么样?



我不知道这个问题是什么意思。既然,所有的字典都是键值结构,问题不是很清楚。所以,我会回顾一下这三个选择,可能会回答这个问题。



示例2



初始化

  d = {} 

使用

 如果t不在d:
d [ t] = list()
d [t] .append(c)

每个字典值必须初始化为一些有用的结构。在这种情况下,我们检查密钥是否存在;当钥匙丢失时,我们创建钥匙并分配一个空列表。



Setdefault



初始化

  d = {} 

使用

  d.setdefault(t,list())。append c)

在这种情况下,我们利用 setdefault 方法来获取与密钥相关联的值或创建与缺少密钥相关联的新值。



默认dict



初始化

 导入集合
d = collections.defaultdict(list)

使用

  d [t] .append(c)

defaultdict 使用缺省键的初始化函数。在这种情况下,我们提供列表函数,以便为缺少的密钥创建一个新的空列表。


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 I want to make this look like:

0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)

My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like:

# where t = 0, c = (4,7), d = {}

# code 1
d[t].append(c)

Now this causes IDLE to fail. However, if I do:

# code 2
d[t] = []
d[t].append(c)

... this works.

So the question is: why does code 2 work, but code 1 doesn't?

PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through.

解决方案

Let's look at

d[t].append(c)

What is the value of d[t]? Try it.

d = {}
t = 0
d[t]

What do you get? Oh. There's nothing in d that has a key of t.

Now try this.

d[t] = []
d[t]

Ahh. Now there's something in d with a key of t.

There are several things you can do.

  1. Use example 2.
  2. Use setdefault. d.setdefault(t,[]).append(c).
  3. Use collections.defaultdict. You'd use a defaultdict(list) instead of a simple dictionary, {}.


Edit 1. Optimization

Given input lines from a file in the above form: ts, x, y, the grouping process is needless. There's no reason to go from a simple list of ( ts, x, y ) to a more complex list of ( ts, (x,y), (x,y), (x,y), ... ). The original list can be processed exactly as it arrived.

d= collections.defaultdict(list)
for ts, x, y in someFileOrListOrQueryOrWhatever:
    d[ts].append( (x,y) )


Edit 2. Answer Question

"when initialising a dictionary, you need to tell the dictionary what the key-value data structure will look like?"

I'm not sure what the question means. Since, all dictionaries are key-value structures, the question's not very clear. So, I'll review the three alternatives, which may answer the question.

Example 2.

Initialization

d= {}

Use

if t not in d:
    d[t] = list()
d[t].append( c )

Each dictionary value must be initialized to some useful structure. In this case, we check to see if the key is present; when the key is missing, we create the key and assign an empty list.

Setdefault

Initialization

d= {}

Use

d.setdefault(t,list()).append( c )

In this case, we exploit the setdefault method to either fetch a value associated with a key or create a new value associated with a missing key.

default dict

Initialization

import collections
d = collections.defaultdict(list)

Use

d[t].append( c )

The defaultdict uses an initializer function for missing keys. In this case, we provide the list function so that a new, empty list is created for a missing key.

这篇关于在Python字典中存储和更新列表:为什么会发生这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆