【问题标题】:While loop/ for loop: How to print together results from different loops?While循环/ for循环:如何将不同循环的结果一起打印?
【发布时间】:2021-10-12 13:51:24
【问题描述】:

我无法编写正确的打印代码 (T, sol_h)。

sol_h 是一个 np。与 T 大小相同的数组。

当打印 (T) 时,您会得到类似于:

0.00
5.00
10.00
15.02
20.03
25.05
30.06
35.07
40.08
45.08
50.10
...

下面的代码只打印T:

start_time = time.time() 
impact_time= sol.t_events[3] # = 154.75 s  

sol_h = sol.y[0]
# solution from a previous function

While True:
    current_time = time.time() 
    elapsed_time = current_time - start_time
    T = '{:.02f}'.format(elapsed_time)
    time.sleep(5)
    print(T)
    
    if elapsed_time > impact_time:
        print ("Impact has occured")
        break
print (Loop has finished)

此代码仅打印 h:

for h in sol_h:
    print(h)

# Result
0.0
242.18277624405562
1016.2986152430877
2397.4567532549913
4463.395396560339
7289.10447523776
...

有没有办法打印(T,h),让它看起来像这样?

0.00, 0.0
5.00, 242.18277624405562
10.00, 1016.2986152430877
15.02, 2397.4567532549913
20.03, 4463.395396560339
25.05, 7289.10447523776
...,   ...

我愿意更改整个代码,以获得正确的 print(T,h)

【问题讨论】:

  • T 不是一个数组,它是一个包含格式化的经过时间的字符串。
  • 哦,是的。没错。

标签: python loops for-loop while-loop


【解决方案1】:

将打印时间并调用time.sleep() 的代码放在for 循环中

for h in sol_h:
    current_time = time.time() 
    elapsed_time = current_time - start_time
    T = '{:.02f}'.format(elapsed_time)
    print(T, h)

    time.sleep(5)

    if elapsed_time > impact_time:
        print ("Impact has occured")
        break

【讨论】:

  • 感谢您的回答。我想要的是每 5 秒将 T 打印在 h 旁边。当我使用您提供的代码时,打印了一行 (T,h)
【解决方案2】:

在 print 调用 print T 时,您可以使用 end = ',',这不会在下一次打印之前导致换行。 看下面的例子

T = [0.00,5.00,10.00,15.00,20.00]
h = [0.00,242.18,1016.29,2397.45,4463.39,7289.10]
for index in range(len(T)):
     print(T[index],end=',')
     print(h[index])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多