问题
(If you have a better title, do edit, I couldn't explain it properly! :) So this is my code:
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)
And this is cipher.txt
:
xli uymgo fvsar jsb
I'm supposed to print out the letters used and how many times they are used, my code works, but I need it alphabetical, I tried putting them in a list list(a)
and then sorting them, but i didn't quite get it, any ideas? Thanks in advance!
回答1:
Whenever dealing with counting, you can use collections.Counter here:
>>> 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)]
If you can't import any modules, then you can append a
to a list and then sort it:
new = []
for i in f:
new.append(i + ' ' + str(f.count(i)) # Note that i is a string, so str() is unnecessary
Or, using a list comprehension:
new = [i + ' ' + str(f.count(i)) for i in f]
Finally, to sort it, just put sorted()
around it. No extra parameters are needed because your outcome is alphabetical :).
回答2:
Here's a oneliner without imports:
{s[i]: n for i, n in enumerate(map(s.count, s))}
And in alphabetical order (if the above is d
):
for k in sorted(d): print k, d[k]
Or another version (oneliner alphabetical):
sorted(set([(s[i], n) for i, n in enumerate(map(s.count, s))]))
来源:https://stackoverflow.com/questions/18568309/how-to-count-characters-in-a-file-and-print-them-sorted-alphanumerically