擅长:python、mysql、java
<p>使用内置的<a href="http://docs.python.org/library/functions.html#map" rel="nofollow">map function</a>:</p>
<pre><code>data=[]
mytuple=()
while True:
myinput=raw_input("Enter two integers: ")
if not myinput:
print("Finished")
break
else:
myinput=map(int,myinput.split(",")) # (1)
data.append(myinput)
mytuple=tuple(data)
print(data)
# [[1, 2], [3, 4]]
print(mytuple)
# ([1, 2], [3, 4])
print(' '.join('{0:4d}'.format(sum(t)) for t in mytuple)) # (2)
# 3 7
</code></pre>
<ol>
<li>使用<code>map(int,...)</code>将字符串转换为整数。还要注意原始代码中有一个错误。<code>myinput.split(",")</code>是表达式,而不是赋值。要更改<code>myinput</code>的值,您必须说<code>myinput = myinput.split(...)</code>。</li>
<li>使用<code>map(sum,...)</code>将sum应用于<code>mytuple</code>中的每个元组。</li>
</ol>