<p>您可以将行更改为:</p>
<pre><code>for i in range(len(a)):
lister.append(int(a[i]))
return sum(lister) % 10 == 0 or sum(lister) == 0
</code></pre>
<p>最后一行将<code>return True</code>如果<strong>条件是<code>True</code>或<code>False</code>如果<strong>两者都不是<code>True</code></p>
<p>您也可以只迭代一个并使用列表comp:</p>
<pre><code>lister = [int(i) for i in a ]
return sum(lister) % 10 == 0 or sum(lister) == 0
</code></pre>
<p>您还可以进一步优化,只需使用<a href="https://docs.python.org/2/reference/expressions.html#generator-expressions" rel="nofollow">generator expression</a>计算一次和:</p>
<pre><code>lister_sum = sum(int(i) for i in a )
return lister_sum % 10 == 0 or lister_sum == 0
</code></pre>
<p>您的初始检查可以使用<a href="https://docs.python.org/2/library/functions.html#all" rel="nofollow">all</a>函数和<a href="https://docs.python.org/2/library/stdtypes.html#str.isdigit" rel="nofollow">str.isdigit</a>检查所有数字,这样您就可以删除<code>try/except</code>:</p>
<pre><code>if len(S) != 19 or not all(x.isdigit() for x in a)
</code></pre>
<p>所以你的最终功能是:</p>
<pre><code>def check(s):
# split into individual strings
spl = s.split()
# make sure format is #### #### #### ####
if len(spl) != 4 or not all(len(x) == 4 for x in spl):
return False
a = s.replace(" ","")
elif len(s) != 19 or not all(x.isdigit() for x in a):
return False
lister_sum = sum(int(i) for i in a)
return lister_sum % 10 == 0
</code></pre>
<p>使用try/除了使用<a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow">map</a>:</p>
<pre><code>def check(s):
if len(s) != 19:
return False
spl = s.split()
if len(spl) != 4 or not all(len(x) == 4 for x in spl):
return False
a = s.replace(" ","")
try:
a = list(map(int,a))
except ValueError:
return False
return sum(a) % 10 == 0
</code></pre>