新程序员在这里。因此,在我下面的代码中,“year1”集合就像它应该的那样工作并且向我吐出一些年份。虽然当我尝试为“year2”设置同样的东西时,它向我吐出的唯一东西是“set()”。
我想知道这样做的代码是怎么回事?感谢您提前提供任何帮助!
def compare(word1, word2, startDate, endDate):
with open('all_words.csv') as allWords:
readWords = csv.reader(allWords, delimiter=',')
year1 = set()
for row in readWords:
if int(startDate) <= int(row[1]) < int(endDate):
if row[0] == word1:
year1.add(row[1])
year2 = set()
for row in readWords:
if int(startDate) <= int(row[1]) < int(endDate):
if row[0] == word2:
year2.add(row[1])
答案 0 :(得分:2)
此时,您创建year2
您已经阅读了整个文件(您已经在它的末尾)。所以你应该seek()
到文件的开头再次通过它。所以:
....
allWords.seek(0)
year2 = set()
....
答案 1 :(得分:0)
如上所述,如果没有重置,则无法迭代文件两次。您的流程中有重复的代码 - 您可以将重复分解出来并只迭代一次。
def compare(word1, word2, startDate, endDate):
with open('all_words.csv') as allWords:
readWords = csv.reader(allWords, delimiter=',')
year1 = set()
year2 = set()
for row in readWords:
if int(startDate) <= int(row[1]) < int(endDate):
if row[0] == word1:
year1.add(row[1])
if row[0] == word2:
year2.add(row[1])