2017-05-19 134 views
-1

我正在嘗試使用計數器按出現次數對字母進行排序,並將具有相同頻率的字母按字母順序排列,但無法訪問字典的值它產生。按頻率排序計數器,然後在Python中按字母順序排序

letter_count = collections.Counter("alphabet") 
print(letter_count) 

生產:

Counter({'a': 2, 'l': 1, 't': 1, 'p': 1, 'h': 1, 'e': 1, 'b': 1}) 

我怎樣才能得到它下令頻率,然後按字母順序排列,所以一切只能一次顯示出來是按字母順序排列?

+0

可以使用適當命名的'letter_count.values訪問值()'。 –

+0

@OP,你可以通過澄清你的意圖來幫助我們。按照字母順序打破關係的頻率,還是按照單次出現的字母排序*整個*計數器? –

回答

2

這聽起來像你的問題是如何按頻率排序整個列表,然後按字母順序打破關係。您可以排序整個列表是這樣的:如果你想輸出是一個字典仍然

>>> a = sorted(letter_count.items(), key=lambda item: (-item[1], item[0])) 
>>> print(a) 
# [('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)] 

,你可以將它轉換成一個collections.OrderedDict

>>> collections.OrderedDict(a) 
# OrderedDict([('a', 2), 
#    ('b', 1), 
#    ('e', 1), 
#    ('h', 1), 
#    ('l', 1), 
#    ('p', 1), 
#    ('t', 1)]) 

這將保留排序,如你可以看到。首先是因爲它是最常見的,所以'a'。其他一切按字母順序排序。

+1

我不明白這是如何「得到所有隻發生過一次的字母」 –

+1

據我所知,這是因爲兩次出現的入口已經放在列表的前面; OP要求按字母順序打破hapax之間的聯繫。 –

+0

公平點。現在就躲過那種語法。 –

0

以這種方式:

for l in letter_count: 
    if letter_count[l] == 1: 
     print(l) # or do what you want 

需要注意的是在按鍵上(你的信)集合迭代在foreach。 然後你是否與鍵關聯的值正好是1

+0

這不會對結果排序。 –

+0

問題已由OP澄清;你可能想要更新你的答案。 –

1

你可以試試這個:

letter_count = collections.Counter("alphabet") 

the_letters = [a for a, b in letter_count.items() if b == 1] 
letters.sort() 
print("letters that occur only once:") 

for i in the_letters: 
    print(i) 

此代碼創建使用列表理解只出現一次的所有字母的列表,然後全部打印出來。 items()返回一個鍵值對,它可以用來確定一個鍵的值是否等於1。

+0

問題已由OP澄清;你可能想要更新你的答案。 –

1

爲了完整起見,以獲得單字母出現的字母順序:

letter_count = collections.Counter("alphabet") 

single_occurrences = sorted([letter for letter, occurrence in letter_count.items() if occurrence == 1]) 
print(single_occurrences) 
# prints: ['b', 'e', 'h', 'l', 'p', 't'] 
+0

問題已由OP澄清;你可能想要更新你的答案。 –

相關問題