字典与Python中不同类型的数组作为值 [英] Dictionary with array of different types as value in Python
问题描述
我正在学习Python,我有一本这样的字典:
category = {World news:[0] ,政治:[0],...}
文件。每篇文章都有一个类别。所以我想要0我必须每个键增加1,当一个类别满足,并增加数组每个键与它发现的文章。所以输出将是:
category = {世界新闻:[2,foo bla content of,content第二篇],
pre>
政治:[1,只有1篇文章],
...
}
这是我现在所在的:
iter_reader:
category [row [4]] [0] = category [row [4]] [0] + 1
category [row [4]]。append(category [row [3]] )
但我认为它将文章解释为关键字,并引发相关错误:
文件./wordCloud.py,第41行,
category [row [4]]。append(category [row [3 ]])
KeyError:当苹果公司在2010年1月推出时。
行[4]
是文章的类别。
row [3]
是本文的内容。
正如Bryan Oakley所说,不需要一个柜台,所以我现在正在这个方向思考...
解决方案在第三行,你是附加
category [row [3]]
您应该可以简单地附加row [3]
。您目前正在使用row [3]
作为类别列表的索引,但我怀疑行[3]
是实际上你想追加的内容。I am learning Python and I have a dictionary like this:
category = { "World news": [0], "Politics": [0], ... }
where now I am reading articles from a file. Every article has a category. So I would like the 0 I have to every key to be incremented by 1 when a category is meet and to augment the array every key has with the article it found. So the output would be:
category = { "World news": [2, "foo bla content of", "content of 2nd article"], "Politics": [1, "only 1 article here"], ... }
Here is what I have now:
for row in iter_reader: category[row[4]][0] = category[row[4]][0] + 1 category[row[4]].append(category[row[3]])
but I think it interprets an article as a key and throws a relevant error:
File "./wordCloud.py", line 41, in category[row[4]].append(category[row[3]]) KeyError: 'When Apple unveiled its in January 2010..
Any ideas please?
row[4]
is the category of the article.row[3]
is the content of the article.As Bryan Oakley said, I do not need to keep a counter, so I am now thinking in this direction...
解决方案In the third line, you are appending
category[row[3]]
where you should probably be appending simplyrow[3]
. You are currently usingrow[3]
as an index for the category list, but I suspectrow[3]
is actually the content you want to append.这篇关于字典与Python中不同类型的数组作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!