python 2.7 - counting occurrence of name in list of namedtuple (the name is in a nested tuple) -
python 2.7 - counting occurrence of name in list of namedtuple (the name is in a nested tuple) -
as title says, i'm trying count occurrence of name in list of namedtuples, name i'm looking in nested tuple. assignment school, , big part of code given. construction of list follows:
paper = namedtuple( 'paper', ['title', 'authors', 'year', 'doi'] ) (id, paper_info) in summaries.iteritems(): summaries[id] = paper( *paper_info ) it easy number of unique titles each year, since both 'title' , 'year' contain 1 value, can't figure out how count number of unique authors per year.
i don't expect guys give me entire code or something, if give me link tutorial subject help lot. did google around lot, cant find helpful information!
i hope i'm not asking much, first time inquire question here.
edit: responses far. code have now:
authors = [ auth paper in summaries.itervalues() auth in paper.authors ] authors the problem is, list of authors code. want them linked year tough, can check amount of unique authors each year.
for keeping track of unique objects, using set. set behaves mathematical set in can have @ 1 re-create of given thing in it.
from collections import namedtuple # convention, instances of `namedtuple` should 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() paper in papers: authors.update(paper.authors) # "authors = union(authors, paper.authors)" print(authors) print(len(authors)) output:
{'j. spolsky', 'r. ward', 'j. atwood', 's. saffron'} 4 more compactly (but perhaps less readably), build authors set doing:
authors = set([author paper in papers author in paper.authors]) this may faster if have big volume of info (i haven't checked), since requires fewer update operations on set.
python-2.7 namedtuple
Comments
Post a Comment