[英]how do I print only the last result in a 'for' loop
How can I print only the final result of a 'for' loop? 如何仅打印“ for”循环的最终结果? For example, here I want the print only the last result (and not all of them):
例如,在这里我只想打印最后的结果(而不是全部):
A=[1,2.5,3,4,5]
a=A[1::2]
b=A[0::2]
c=b[0]
for num in b:
c=c*num
print sum(a),c
you can use the for/else pattern: 您可以使用for / else模式:
a = 1
for i in xrange(1, 10):
a *= i
else:
print a
Use a variable: 使用变量:
A=[1,2.5,3,4,5]
a=A[1::2]
b=A[0::2]
c=b[0]
for num in b:
c=c*num
l=sum(a),c
print(l)
as mattias said, just put the print outside the for loop, like this 正如mattias所说,只需将打印内容放在for循环之外,像这样
A=[1,2.5,3,4,5]
a=A[1::2]
b=A[0::2]
c=b[0]
for num in b:
c=c*num
print sum(a),c #notice that is now outside the loop
at the end of the loop c
would have it latest calculate value from the for-loop which then you can print it or do whatever you want with it 在循环的末尾,
c
会将其从for循环中获取最新的计算值,然后您可以打印该值或使用它进行任何操作
尝试for i in range(len(b)):
使用for i in range(len(b)):
然后if i == len(b)-1: execute code
而不是for循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.