擅长:python、mysql、java
<p>最简单的方法是使用<a href="http://en.wikipedia.org/wiki/Integer_division#Division_of_integers" rel="nofollow">integer division</a>(<code>//</code>)和<a href="http://en.wikipedia.org/wiki/Modulo_operation" rel="nofollow">modulus</a>(<code>%</code>)函数,用0年以来的月数表示月份:</p>
<pre><code>months = year * 12 + month - 1 # Months since year 0 minus 1
tuples = [((months - i) // 12, (months - i) % 12 + 1) for i in range(10)]
</code></pre>
<p>当我们稍后将1添加到模函数的结果中以获得1索引时,需要<code>- 1</code>表达式中的<code>months</code>才能得到正确的答案(即月从1到12而不是0到11)。</p>
<p>或者您可能要创建生成器:</p>
<pre><code>def year_month_tuples(year, month):
months = year * 12 + month - 1 # -1 to reflect 1-indexing
while True:
yield (months // 12, months % 12 + 1) # +1 to reflect 1-indexing
months -= 1 # next time we want the previous month
</code></pre>
<p>可用于:</p>
<pre><code>>>> tuples = year_month_tuples(2011, 7)
>>> [tuples.next() for i in range(10)]
</code></pre>