如何对字典进行排序并仅获取第一个和最后一个元素

时间:2015-10-19 02:18:39

标签: python

我写了一个程序,其中我正在计算字符串中出现的字母的频率。

Input: AAAABBBBBCCDEEEEEEEEEEFFF

我希望我的输出只是那些发生次数最多且最少次数的字母,以及它们发生的次数。

import sys
seq=sys.argv[1]
count = {}
for i in seq:
  if count.has_key(i):
    count[i] += 1
  else:
    count[i] = 1

for i in sorted(count, key=count.get, reverse=True):
  print i, count[i]

输出:

 Actual Output:
 E:10, B:5, A:4, F:3, C:2, D:1

Expected Output:
E: 10 , D: 1

2 个答案:

答案 0 :(得分:4)

您可以使用collections.Counter来计算字母:

>>> import operator, collections
>>> counter = collections.Counter('AAAABBBBBCCDEEEEEEEEEEFFF')
Counter({'E': 10, 'B': 5, 'A': 4, 'F': 3, 'C': 2, 'D': 1})

>>> sorted_counter = sorted(counter, key=operator.itemgetter(1), reverse=True)
[('E', 10), ('B', 5), ('A', 4), ('F', 3), ('C', 2), ('D', 1)]   

>>> print sorted_counter[-1]
('D', 1)

>>> print sorted_counter[0]
('E', 10)

答案 1 :(得分:0)

你几乎就在那里。您没有理由在整个排序字典上进行迭代。

  public clsOrder(string strDescription,
    int intQuantity, decimal decPrice)
  {    
    this.Description = strDescription;
    this.Quantity = intQuantity;
    this.Price = decPrice;
  }

  public clsCustomer(string strName,
    string strStreet, string strCity,
    string strState, string strZip)
  {
    this.Name = strName;
    this.Street = strStreet;
    this.City = strCity;
    this.State = strState;
    this.Zip = strZip;
  }

可替换地:

sorted_count = sorted(count, key=count.get, reverse=True)
print sorted_count[0]
print sorted_count[-1]