2011-05-27 70 views
0

使用Python,我試圖打印出一張表格,其中包含基於一組數據的整理信息。對多個變量進行分組並計數唯一組合的數量

Data 1 - 'Car', 'Cadillac','Blue'

Data 2 - 'Car', 'Aston Martin','Black'

Data 3 - 'Car', 'Cadillac', 'Blue'

現在我需要找到相同的組合發生的次數 - 即我想打印的'Car'組合,'Cadillac''Blue'出現兩次,另一次出現一次。我如何在Python中做到這一點?

編輯:我正在使用Python 2.4!

+0

看起來像功課 – tback 2011-05-27 10:31:55

+0

我是一個初學者,其實。你至少能告訴我哪個數據類型開頭? – GPX 2011-05-27 10:32:52

+0

但是 - 如果它的功課:請使用標籤'家庭作業'! – phynfo 2011-05-27 10:36:25

回答

2

首先對字符串進行元組化,並將其全部放入列表中;然後用count

>>> list 
[('Car', 'Cadillac','Blue'), ('Car', 'Aston Martin','Black'), ('Car', 'Cadillac', 'Blue'), ...] 
>>> list.count(('Car', 'Cadillac', 'Blue')) 
1 
+0

當它應該是'2'時給出結果'1'並不是非常有用... – vartec 2011-05-27 10:42:19

1
>>> from collections import Counter 
>>> Counter(['apple','red','apple','red','red','pear']) 
Counter({'red': 3, 'apple': 2, 'pear': 1}) 

Collections in docs.python.org可在Python 2.7

編輯:

列表的方式與Python兼容2.4

In [1]: cars = [('Car', 'Cadillac', 'Blue'), ('Car', 'Aston Martin', 'Black'), ('Car', 'Cadillac', 'Blue')] 

In [2]: cars.count(('Car', 'Cadillac', 'Blue')) 
Out[2]: 2 
+0

我被2.4卡住了! – GPX 2011-05-27 10:44:57

+0

Outch!那麼其他人提供的列表方法可能是前進的方向...... – 2011-05-27 10:48:11

0

Python允許任何哈希的,不可變對象是詞典中的鍵,所以你可以使用元組('Car', 'Cadillac', 'Blue')作爲一個關鍵。你可以用collections.Counter

0

您可以使用Python Counter

>>> from collections import Counter 
>>> list = [('car','astin'),('car','cadillac'),('car','astin')] 
>>> Counter(list) 
Counter({('car', 'astin'): 2, ('car', 'cadillac'): 1})