Python Beginner - How to splice a list of objects with the frequency of an object's attribute -
given:
from collections import counter class test: age = 'unknown' city = 'unknown' def __init__(self, a, c): self.age = self.city = c def __repr__(self): return "(" + str(self.age) + "," + self.city + ")" l = [test(20, 'la'), test(30, 'ny'), test(30, 'la')]
i count frequency of 'city' attribute:
desired output:
[[20, 'la', 2], [30, 'ny', 1], [30, 'la', 2]]
you're on right track if you're thinking using counter
- can't splicing want, will frequencies you. since want frequencies based on city, tell counter
cities:
freq = counter(l.city l in l)
then freq['la']
frequency associated 'la'
. want list of tuples (age, city, frequency)
- objects in l
give age , city directly, , have object gives frequency when give city. means can desired result simple list comprehension:
[(l.age, l.city, freq[l.city]) l in l]
Comments
Post a Comment