2014-10-31 39 views
0

正如标题所说,我试图计算namedtuples列表中名称的出现次数,名称是我正在查找的名称在嵌套元组中。 这是一个学校的任务,并给出了很大一部分代码。 列表的结构如下:在namedtuple列表中计算名称的发生(名称位于嵌套元组中)

paper = namedtuple('paper', ['title', 'authors', 'year', 'doi']) 

for (id, paper_info) in Summaries.iteritems(): 
    Summaries[id] = paper(*paper_info) 

这是很容易获得的每年独特的游戏,数量,因为这两个“标题”和“年”包含一个值,但我想不出了解如何统计每年唯一作者的数量。

我不指望你们给我整个代码或其他东西,但如果你能给我一个关于这个主题的好教程的链接,这将有很大帮助。 我做了很多谷歌,但我找不到任何有用的信息!

我希望我不要问太多,第一次我在这里问一个问题。编辑: 感谢迄今为止的回应。这是我现在的代码:

authors = [ 
    auth 
    for paper in Summaries.itervalues() 
    for auth in paper.authors 
    ] 

authors 

问题是,我只列出了所有这些代码的作者。我希望他们与年度强硬有关,所以我可以检查每年独特作者的数量。

回答

0

为了跟踪独特的物体,我喜欢使用set。 A set的行为类似于数学集,因为它最多只能包含任何给定内容的一个副本。

from collections import namedtuple 

# by convention, instances of `namedtuple` should be in UpperCamelCase 
Paper = namedtuple('paper', ['title', 'authors', 'year', 'doi']) 

papers = [ 
    Paper('On Unicorns', ['J. Atwood', 'J. Spolsky'], 2008, 'foo'), 
    Paper('Discourse', ['J. Atwood', 'R. Ward', 'S. Saffron'], 2012, 'bar'), 
    Paper('Joel On Software', ['J. Spolsky'], 2000, 'baz') 
    ] 

authors = set() 
for paper in papers: 
    authors.update(paper.authors) # "authors = union(authors, paper.authors)" 

print(authors) 
print(len(authors)) 

输出:

{'J. Spolsky', 'R. Ward', 'J. Atwood', 'S. Saffron'} 
4 

更紧凑(也可能不太可读取),你可以构建authors设置这样做:

authors = set([author for paper in papers for author in paper.authors]) 

,如果你有这可能会更快大量的数据(我没有选中),因为它需要更少的更新操作。

0

如果您不想使用嵌入类型set()并且想了解逻辑,请使用列表和if分叉。

如果我们不senshin的代码中使用set()

# authors = set() 
# for paper in papers: 
#  authors.update(paper.authors) # "authors = union(authors, paper.authors)" 

authors = [] 
for paper in papers: 
    for author in paper.authors: 
     if not author in authors: 
      authors.append(author) 

你可以得到类似的结果senshin的。我希望它有帮助。