如何计算文件中的字符并按字母数字顺序打印

发布于 2021-01-29 15:02:34

(如果标题更好,请进行编辑,我无法正确解释!:)这是我的代码:

with open('cipher.txt') as f:
    f = f.read().replace(' ', '')

new = []
let = []
for i in f:
    let.append(i)
    if i.count(i) > 1:
        i.count(i) == 1
    else:
        new = sorted([i + ' ' + str(f.count(i)) for i in f])
for o in new:
  print(o)

这是cipher.txt

xli uymgo fvsar jsb

我应该打印出使用过的字母以及使用了多少次,我的代码可以正常工作,但是我需要按字母顺序排列,我尝试将它们放在列表中list(a)然后进行排序,但是我不太明白想法?提前致谢!

关注者
0
被浏览
138
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    每当进行计数时,您都可以collections.Counter在这里使用:

    >>> from collections import Counter
    >>> print sorted(Counter('xli uymgo fvsar jsb'.replace(' ', '')).most_common())
    [('a', 1), ('b', 1), ('f', 1), ('g', 1), ('i', 1), ('j', 1), ('l', 1), ('m', 1), ('o', 1), ('r', 1), ('s', 2), ('u', 1), ('v', 1), ('x', 1), ('y', 1)]
    

    如果您无法导入任何模块,则可以追加a到列表中然后对其进行排序:

    new = []
    for i in f:
        new.append(i + ' ' + str(f.count(i)) # Note that i is a string, so str() is unnecessary
    

    或者,使用列表推导:

    new = [i + ' ' + str(f.count(i)) for i in f]
    

    最后,要对其进行排序,只需将sorted()其放在周围即可。不需要额外的参数,因为您的结果是按字母顺序排列的:)。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看