如何按字母顺序排列词典?

2024-09-28 21:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

def wordCount(inPath):
    inFile = open(inPath, 'r')
    lineList = inFile.readlines()
    counter = {}
    for line in range(len(lineList)):
        currentLine = lineList[line].rstrip("\n")
        for letter in range(len(currentLine)):
            if currentLine[letter] in counter:
                counter[currentLine[letter]] += 1
            else:
                counter[currentLine[letter]] = 1

    sorted(counter.keys(), key=lambda counter: counter[0])
    for letter in counter:
        print('{:3}{}'.format(letter, counter[letter]))

inPath = "file.txt"
wordCount(inPath)

这是输出:

^{pr2}$

这是我想要的输出:

  12
A 1
H 1
T 1
a 1
c 2
d 1
e 10
f 2
h 5
i 6
k 1
l 2
n 5
o 3
r 4
s 5
t 5
u 1
x 1

如何按字母顺序对“计数器”排序? 我尝试过简单地按键和值排序,但它没有按字母顺序从大写字母开始返回 谢谢你的帮助!在


Tags: inforlen排序顺序字母linecounter
1条回答
网友
1楼 · 发布于 2024-09-28 21:42:26
sorted(counter.keys(), key=lambda counter: counter[0])

单独做什么都不做:它返回一个根本不使用的结果(除非您使用_调用它,但这是一个命令行实践)

与使用list.sort()方法所能做的不同,您不能“就地”排序字典键。但您可以在键的排序版本上迭代:

^{pr2}$

, key=lambda counter: counter[0]在这里没用:你的钥匙里只有字母。

撇开这一点,你可以用简化的代码来计算整个字母。

import collections

c = collections.Counter("This is a Sentence")
for k,v in sorted(c.items()):
    print("{} {}".format(k,v))

结果(包括空格字符):

  3
S 1
T 1
a 1
c 1
e 3
h 1
i 2
n 2
s 2
t 1

相关问题 更多 >