我正在尝试让我的程序输出:
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”时循环回到字母表的开头。
第二部分,单词,是它从字符串中扫描的按字母顺序排列的单词。
第三部分,是{一个词出现的次数:它出现的句子数}。
出于某种原因,除了我无法让枚举循环在刻字上正常工作之外,一切正常。它目前输出:
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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句