簡體   English   中英

以字母順序返回字典鍵和值

[英]Return dictionary keys and values in alphabetical order

我正在嘗試在Python指南中進行此練習:

編寫一個程序,該程序讀取命令行上的字符串,並按字母順序返回該字符串中出現的字母表字母表以及每個字母出現的次數。 大小寫應忽略。 該程序的示例運行如下所示:

$ python letter_counts.py "ThiS is String with Upper and lower case Letters."
a  2
c  1
d  1
e  5
g  1
h  2
i  4
l  2
n  2
o  1
p  2
r  4
s  5
t  5
u  1
w  2
$

我已經編寫了一個函數來對字母進行計數並將它們及其對應的值存儲在字典中:

def count_all(text):
    text = text.lower()
    counts = {}
    for char in text:
        if char not in counts:
            counts.setdefault(char,1)
        else:
            counts[char] = counts[char] + 1
    print(counts)

但是我很ham愧地說我完全不知道如何使用任何種類的規則來訂購映射類型的項目。 我需要將它們轉換為列表嗎? 我是否需要在任何時候使用ord()

編輯:根據我得到的答案,我設法使函數按字母順序打印出項目,而不必使用我尚不完全了解的任何方法。 這是完整的東西:

def count_all(text):
    text = text.lower()
    counts = {}
    for char in text:
        if char not in counts:
            counts.setdefault(char,1)
        else:
            counts[char] = counts[char] + 1
    counts = sorted(counts.items())
    for i in counts:
        print(i[0],' ',i[1])

count_all('banana')

這是一個好的解決方案嗎? 如何改善?

count_all函數中添加return語句以返回字典

def count_all(text):
    ...
    return counts

然后,您可以使用已sorted內置函數和for循環:

for e in sorted(count_all("ThiS is String with Upper and lower case Letters").items()):
    print e[0], e[1]

請注意, some_dict.items()方法將返回(key, value)形式的tuple對。

另外,由於看起來您不想計算“。” 或空格,您可以使用:

text = "".join(text.strip(".").split()).lower()

假設您的數據存儲在字典中:

txt='''\
a  2
c  1
d  1
e  5
g  1
h  2
i  4
l  2
n  2
o  1
p  2
r  4
s  5
t  5
u  1
w  2'''

d=dict([tuple(e.split()) for e in txt.splitlines()])
# d={'p': '2', 'r': '4', 's': '5', 't': '5', 'u': '1', 'w': '2', 'a': '2', 'c': '1', 'd': '1', 'e': '5', 'g': '1', 'h': '2', 'i': '4', 'l': '2', 'n': '2', 'o': '1'}

如果只想通過鍵打印d ,則可以直接使用sorted

print(sorted(d.items()))

現在,如果您要首先按字母的頻率對a)進行排序,然后對b)的字母進行排序:

li=sorted(d.items(), key=lambda t: (t[1], -ord(t[0])), reverse=True)
# li=
('e', '5')
('s', '5')
('t', '5')
('i', '4')
('r', '4')
('a', '2')
('h', '2')
('l', '2')
('n', '2')
('p', '2')
('w', '2')
('c', '1')
('d', '1')
('g', '1')
('o', '1')
('u', '1')
s = 'ThiS is String with Upper and lower case Letters.'

# Or see Python's Counter class: counts = Counter(s.lower())
counts = {}
for c in s.lower():
    counts[c] = counts.get(c, 0) + 1

for c, n in sorted(counts.items()):
    print(c, n)

sorted可以正常工作,並且在stackoverflow上非常流行,但是比sort(2.x和3.x)都慢很多,並且往往會產生過長的代碼行。

所以:

items = list(counts.items())
items.sort()
for key, value in items:
    # do something with key and value

上面的代碼應該在2.x和3.x上都可以使用,盡管未經測試。

如前所述,collections.Counter()更接近於您在這種情況下想要執行的操作,並且在2.x和3.x中都可用。

如果要在循環中進行排序,則需要使用類似字典的樹而不是字典(哈希表)。 但事實並非如此,因此使用字典和單一排序更為有效。

如果您是在循環中進行排序,則以下是Python中的幾本類似字典的樹(支持2.x和3.x,包括jython和pypy),它們以鍵順序保存其數據: http ://stromberg.dnsalias.org /〜dstromberg / datastructures / http://stromberg.dnsalias.org/~strombrg/python-tree-and-heap-comparison/2014-01/

也有所謂的collections.OrderedDict(),但它以插入順序而不是鍵順序存儲數據。

HTH

我做了同樣的作業,設法解決了。 PS:這是我自己的想法,因此可能會有更好的方法。

diction ={}
Input = input()
INPUT = Input.lower()
characterlist = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in characterlist:
    diction[i]= INPUT.count(i,0,100)
    if diction[i]==0:
        del diction[i]

for k in diction:
    print(k,diction[k])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM