简体   繁体   English

我如何只打印“ for”循环中的最后一个结果

[英]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.

相关问题 如何仅打印 for 循环中的最后一个值? - How do I print only the last value in a for loop? 如何仅打印最后一个 output? - How do I print the last output only? 如何在while循环中保存来自输入()function的多个结果,而不是仅在Python中的最后一个结果? - How do i save multiple results from a input() function in a while loop, not the last result only in Python? 我该如何只打印最后一个值? - How do I make this only print the last value? 我如何让我的字典从我的正则表达式循环中打印出更多的值,而不是只打印最后一个值? - How do I get my dictionary to print out more values from my regex loop instead of printing only the last one? 如何从操作循环中以列表形式获取打印输出?,或者,在不打印的情况下获得相同的结果? - How do I get a print output as a list from a manipulated loop?, Or, get same result without print? 除非结果发生变化,否则如何使 while 循环只打印一次结果? - How do I make a while loop print a result just once, unless the result changes? 如何仅打印 python 中总和数组的最后一个结果 - How to print only the last result of an array of sum in python 如何打印第一个和最后一个值? - How do I print the first and last value? For 循环只给出 for 循环的最后一个结果 - For loop only gives last result of for loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM