如果你想要不同國家的數量,你可以簡單地把len
的set
。例如:
class Person(object):
def __init__(self, nation, name):
self.nation = nation
self.name = name
People = [Person("Canada", "Dave"), Person("Scotland", "Alex"), Person("Canada", "Fred"), Person("Japan", "Kenta")]
然後
>>> set(p.nation for p in People)
set(['Canada', 'Japan', 'Scotland'])
>>> {p.nation for p in People} # python 2.7
set(['Canada', 'Japan', 'Scotland'])
>>> len({p.nation for p in People})
3
的(x for x in y)
是「發電機表達」,而{x for x in y}
是「集修真」(僅在2.7+可用 - 它就像一個列表理解。但是對於套)
如果你想更具體的信息,您可以使用一個Counter
對象:
>>> from collections import Counter
>>> c = Counter(p.nation for p in People)
>>> c
Counter({'Canada': 2, 'Japan': 1, 'Scotland': 1})
>>> len(c)
3
>>> sum(c.values())
4
來源
2013-01-14 14:50:35
DSM
+1。我不僅速度太慢,而且對於更完整的答案我太慢了。 –