Input is a string, the idea is to count the letters A-z only, and print them alphabetically with the count of appearances.
As usual I kept at this ’till I got a working result, but now seek to optimize it in order to better understand the Python way of doing things.
def string_lower_as_list(string):
"""
>>> string_lower_as_list('a bC')
['a', ' ', 'b', 'c']
"""
return list(string.lower())
from sys import argv
letters = [letter for letter in string_lower_as_list(argv[1])
if ord(letter) < 124 and ord(letter) > 96]
uniques = sorted(set(letters))
for let in uniques:
print let, letters.count(let)
- How do I remove the duplication of ord(letter) in the list comprehension?
- Would there have been any benefit in using a Dictionary or Tuple in this instance, if so, how?
EDIT
Should have said, Python 2.7 on win32
You can compare letters directly and you actually only need to compare lower case letters
But better would be to use a dictionary to count the values.
letters.counthas to traverse the list every time you call it. But you are already traversing the list to filter out the right characters, so why not count them at the same time?Edit: As the others said, you don’t have to convert the string to a list. You can iterate over it directly:
for letter in argv[1].lower().