I am trying to write a program to draw a histogram of the lengths of words present in a list, so far I am up the stage of increasing the number of words present of a certain length by one every time the loop finds a word with that certain length, at the moment I have:
L = []
for i in range(L):
length = len(i)
for len(i) = 1:
total1 = total1 + 1
for len(i) = 2:
total2= total2 + 1
for len(i) = 3:
total3 = total3 + 1
for len(i) = 4:
total4 = total4 + 1
for len(i) = 5:
total5 = total5 + 1
However clearly this is a stupid method as it involved naming each version of totaln, where in this case n would be up to 11, so my question is can I simply put
L = []
for i in range(L):
length = len(i)
for len(i) = n:
totaln = totaln + 1
to cover all values of n, and then refer to for example total4 later? Or will the interpreter return an error as total4 isn’t explicitly defined?
As for the rest of the code I think I can work that bit out, it’s just this issue I am having trouble with, being very new to programming.
In Python 2.7 or above, you could use a
Counter:prints
which is a dictionary mapping word lengths to frequencies.