<p>你的<code>dance_time</code>是一个字符串。请使用<code>swap_counter <= int(dance_time):</code></p>
<p>一些可能有用的东西:</p>
<p>你不需要临时工。您可以转换代码:</p>
<pre><code> tempchar = listinput[counter]
tempchar = str(tempchar)
tempchar = tempchar.swapcase()
listinput[counter] = tempchar
</code></pre>
<p>至singlr线:</p>
<pre><code> listinput[counter] = str(listinput[counter]),swapcase()
</code></pre>
<p>注意,您只是根据<code>alternate</code>的值交换交替字符的大小写。我猜,虽然在这个例子中设置为<code>0</code>,但在实际的程序中,您会想随意更改它。然后,您可以尝试以下操作:</p>
<pre><code>for i, l in enumerate(listinput):
if alternate == 0:
if i%2 == 1: # odd samples
listinput[i] = str(listinput[i]).swapcase()
elif alternate == 1:
if i%2 == 0: # even samples
listinput[i] = str(listinput[i]).swapcase()
else:
pass
</code></pre>
<p>或者简单地说:</p>
<pre><code>for i, l in enumerate(listinput):
if (alternate+i)%2 == 1: # odd samples
listinput[i] = str(listinput[i]).swapcase()
</code></pre>
<p>这是一样的,假设<code>alterante</code>是<code>0</code>或<code>1</code>,这很容易用<code>if</code>条件检查</p>
<p>最后,请注意Python中的函数是一级值。也可以返回一个函数,并将其作为条件,如下所示:</p>
<pre><code>def evenOdd(alternate):
if alternate == 0: return lambda x: x%2 == 1
elif alternate == 1: return lambda x: x%2 == 0
print [ (l.swapcase() if evenOdd(alternate)(i) else l) for i, l in enumerate(listinput) ]
</code></pre>
<p>这是一个稍微容易阅读</p>
<p>在这里,我又把事情简单化了。如果alternate不是<code>0</code>或<code>1</code>,则可能需要<code>raise</code>函数中的<code>ValueError</code></p>
<p>最后,按照上述示例,您还可以执行以下操作:</p>
<pre><code>[(l.swapcase() if (i+alternate)%2==0 else l) for i, l in enumerate(listinput)]
</code></pre>