2015-10-19 93 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