Python start line with a letter, combining two for loops?

373
May 08, 2017, at 09:27 AM

I'm trying to have my program output:

a. am {1: '2'}
b. at {1: '2'}
c. far {1: '1'}
...
ff. glad {1: '2'}
gg. i {1: '2'}
hh. it {1: '1'}
...
ooo. lets {1: '0'}
ppp. outcome {1: '2'}

The first part, the letters, is the line number but represented with a letter, looping back to the start of the alphabet when it reaches "z."

The second part, the words, is the alphabetized word that it scans from a string.

The third part, is {the number of times a word appears:sentence number(s) it appears in}.

For some reason, everything works except I cannot get the enumeration loop to work correctly on the lettering. It currently outputs this:

a. am {1: '2'}
a. at {1: '2'}
a. far {1: '1'}
a. glad {1: '2'}

My code is:

import string
from itertools import cycle
x=range(1)
...
letters = list(string.ascii_lowercase)
m = len(letters)
for key in sorted(word_counter):
    order = {len(word_counter[key]): str(sent_num[key]).replace('[','').replace(']','')}
        #creates a dictionary with the number of times word appears on the left
        #and the sentence it appears in on the right
    for i, (let, e) in enumerate(zip(cycle(letters), x)):
        testing = (let*(i//m+1))
        print("{}. {} {}".format(testing, key, order)) 

If I change the 'x=range(1)' to anything else it just repeats the previous line that many times then moves onto the next word. Can anyone help me?

Answer 1

You don't need the inner loop, zip your cycle object with the main list and let the counting go on from there:

...
for i, (let, key) in enumerate(zip(cycle(letters), sorted(word_counter))):
    order = {len(word_counter[key]): str(sent_num[key]).replace('[','').replace(']','')}
    testing = let*(i//m+1)
    print("{}. {} {}".format(testing, key, order)) 
READ ALSO
pandas groupby id and month

pandas groupby id and month

this is the demo example of my dataframe

437
multiply matrix by itself in python (H.W)

multiply matrix by itself in python (H.W)

I need to write a program that multiply matrix (nXn) by itselfI have to calculate the max and min during the process and not in the end

351