Python 以字母开头的行,结合两个 for 循环?

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

我正在尝试让我的程序输出:

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'}

第一部分,字母,是行号,但用字母表示,当它到达 "z."

时循环回到字母表的开头

第二部分,单词,是它从字符串中扫描的按字母顺序排列的单词。

第三部分,是{一个词出现的次数appears:sentence个数}。

出于某种原因,一切正常,除了我无法让枚举循环在字母上正常工作。它目前输出这个:

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

我的代码是:

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)) 

如果我将 'x=range(1)' 更改为其他任何内容,它只会重复上一行多次,然后移动到下一个单词。谁能帮帮我?

您不需要内部循环,zip 您的 cycle 对象与主列表并让计数从那里继续:

...
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))