python - Reduce list of lists if entries match -
i have list in python looks like
[['boy','121','is male child'],['boy','121','is male'],['boy','121','is child'],['girl','122','is female child'],['girl','122','is child']]
i want reduce list based on first 2 entries in each list, get
[['boy','121',is male child, male, child'],['girl','122','is female child','is child']]
is there way efficiently without creating dummy list?
as more pythonic way such task can use dictionary :
>>> li=[['boy','121','is male child'],['boy','121','is male'],['boy','121','is child'],['girl','122','is female child'],['girl','122','is child']] >>> >>> d={} >>> >>> i,j,k in li: ... d.setdefault((i,j),[]).append(k) ... >>> d {('boy', '121'): ['is male child', 'is male', 'is child'], ('girl', '122'): ['is female child', 'is child']}
if key in dictionary, return value. if not, insert key value of default , return default. default defaults none.
and if want have elements within 1 container can loop on items , convert value tuple
ad key:
>>> [i+tuple(j) i,j in d.items()] [('boy', '121', 'is male child', 'is male', 'is child'), ('girl', '122', 'is female child', 'is child')]
as @jonrsharpe says more elegant way can use collections.defaultdict
:
>>> collections import defaultdict >>> >>> d=defaultdict(list) >>> i,j,k in li: ... d[i,j].append(k) ... >>> d defaultdict(<type 'list'>, {('boy', '121'): ['is male child', 'is male', 'is child'], ('girl', '122'): ['is female child', 'is child']})
Comments
Post a Comment