[英]how to add numbering inside the for loop?
I have a problem printing the line with the number.我在打印带有数字的行时遇到问题。 How to add numbering before of line?如何在行前添加编号? I made a comment on which part.我评论了哪一部分。
f = open('filename', "r")
lines = f.readlines()
for line in lines:
synonyms = []
print(line) # I want my interface to be, 1. word 2. word, and so on
answer = input("Answer: ").lower()
for syn in wordnet.synsets(line.strip()):
for l in syn.lemmas():
synonyms.append(l.name())
My code is just printing我的代码只是打印
word1单词1
Answer:回答:
word2字2
Answer:回答:
My ideal code is:我理想的代码是:
1.word1 1.word1
Answer:回答:
2.word2 2.word2
Answer:回答:
replace your loop:替换你的循环:
for i, line in enumerate(lines):
print(str(i) + '. ' + str(line))
"i" will be the number waited... “i”将是等待的号码...
you could use string interpolation if you are at min python3.6如果你在最低 python3.6,你可以使用字符串插值
print(f'{i}. {line}')
Instead of traversing through every line in the lines
list, just go through the indexes of every element, and then print the index+1
, as obviously list indexes start from 0, but we want our numbering to start from 1. So, instead of printing only the line, we'll print line_no: line
而不是遍历lines
列表中的每一行,只需 go 通过每个元素的索引,然后打印index+1
,显然列表索引从 0 开始,但我们希望我们的编号从 1 开始。所以,而不是只打印行,我们将打印line_no: line
f = open('filename', "r")
lines = f.readlines()
for line_no in range(len(lines)):
synonyms = []
print(f"{line_no+1}: {lines[line_no]}") # I want my interface to be, 1. word 2. word, and so on
answer = input("Answer: ").lower()
for syn in wordnet.synsets(line.strip()):
for l in syn.lemmas():
synonyms.append(l.name())
Hope my answer helped:D希望我的回答有帮助:D
Try this:尝试这个:
f = open('filename', "r")
lines = f.readlines()
for line_no,line in enumerate(lines):
synonyms = []
print(str(line_no+1)+'.'+line) # I want my interface to be, 1. word 2. word, and so on
answer = input("Answer: ").lower()
for syn in wordnet.synsets(line.strip()):
for l in syn.lemmas():
synonyms.append(l.name())
Add a variable called count
and increment it with each iteration of the for
loop.添加一个名为count
的变量,并在for
循环的每次迭代中递增它。 Code:代码:
count = 1
f = open('filename', "r")
lines = f.readlines()
for line in lines:
synonyms = []
print(str(count) + ". " + line) # I want my interface to be, 1. word 2. word, and so on
count += 1
answer = input("Answer: ").lower()
for syn in wordnet.synsets(line.strip()):
for l in syn.lemmas():
synonyms.append(l.name())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.