这是我的示例代码:
import random
class Test:
def __init__(self, pin, name):
self.Pin = pin
self.Name = name
objects = []
myPinList = [123, 323, 1234, 123, 12314, 1234, 1231, 5754, 5456, 4245, 6573, 5743, 567, 563]
objects.append(Test(random.choice(myPinList), "Jhon"))
objects.append(Test(random.choice(myPinList), "Nimra"))
objects.append(Test(random.choice(myPinList), "Thomas"))
objects.append(Test(random.choice(myPinList), "Treesa"))
objects.append(Test(random.choice(myPinList), "Newt"))
objects.append(Test(random.choice(myPinList), "Greny"))
现在我想计算具有相同PIN属性值的对象总数。
objects_having_same_Pin = ???
我搜索了很多但是没有找到pythonic的方法来做到这一点。
答案 0 :(得分:2)
您可以在此处使用 collections.Counter
:
cnts = Counter([i.Pin for i in objects])
# Counter({1231: 2, 1234: 1, 5456: 1, 5743: 1, 6573: 1})
然后,如果您想要一个总数,只需将所有大于1的值相加:
'{} users share a Pin'.format(sum([i for _, i in cnts.items() if i > 1]))
# '2 users share a Pin'
如果您想知道谁分享图钉,您可以使用 collections.defaultdict
:
dct = defaultdict(list)
for obj in objects:
dct[obj.Pin].append(obj.Name)
# defaultdict(list,
# {1231: ['Jhon', 'Thomas'],
# 1234: ['Nimra'],
# 5456: ['Treesa'],
# 5743: ['Newt'],
# 6573: ['Greny']})