2015-10-19 90 views
1
def frequencies(data): 

    data.sort() 

    count = 0 
    previous = data[0] 

    print("data\tfrequency") # '\t' is the TAB character 

    for d in data: 
     if d == previous: 
      # same as the previous, so just increment the count 
      count += 1 
     else: 
      # we've found a new item so print out the old and reset the count 
      print(str(previous) + "\t" + str(count)) 
      count = 1 

     previous = d 

所以我有這個頻率代碼,但是它每次都在我的列表中留下最後一個數字。Python中的頻率

它可能與我之前開始的位置或可能在最後重置d前的位置有關。

回答

0

您可以使用count來統計列表/序列中的項目。所以,你的代碼可以簡化爲如下所示:

def frequencies(data): 
    unique_items = set(data) 
    for item in unique_items: 
     print('%s\t%s' % (item, data.count(item))) 
+0

謝謝,但我必須保持它的代碼是當前設置方式,只要解決了一行代碼 – carroll

3

對於元素的最後一組,你永遠不會把它們打印出來,因爲你永遠也找不到的東西后不同。循環後您需要重複打印輸出。

但這是相當學術的;在現實世界中,你會更願意使用Counter

from collections import Counter 
counter = Counter(data) 
for key in counter: 
    print("%s\t%d" % (key, counter[key])) 
+0

太感謝你了! ! – carroll