如何格式化“ for”循环以遍历特定的年度日期范围?

时间:2019-02-04 00:51:32

标签: python-3.x

我必须执行一个python程序来检查1987年至2012年的年份,并且该程序必须告诉我该范围内有多少年中有重复的数字。我正在努力为1987-2012年创建一个循环。我必须以某种方式将它们从int转换为字符串,然后再执行代码以计数每个数字。

如何重新编程到下一年(例如从1987年到1988年)?

#years = range(1987,2013)   
year = "1991"


cells = [0,0,0,0,0,0,0,0,0,0]
for x in range(10):
      cells[x] = year.count(str(x))

print("output1=", cells)
print("\n")

for x in range(len(cells)):

    if cells[x] > 1:

        print("for ",year,x,"appears ",cells[x]," times",end=" ")

结果应该看起来像 1987年没有重复的数字 1988年8次出现2次 1989年9次出现2次 1990年9次出现2次

1 个答案:

答案 0 :(得分:0)

扩展AChampion的评论,您可以像这样反复浏览几年:

start_date = 1987
end_date = 2013
counter = 0
for year in range(start_date, end_date): # Creates an iterable containing years 1987-2013
    # A set can only have unique items, so it will discard duplicates 
    # If the length of the set is less than 4, then it had to discard a duplicate
    if len(set(str(year))) != 4: 
        counter += 1
print("This date range has", counter, "years with duplicate numbers")