Printing list of numbers as an array from for loop Python

别等时光非礼了梦想. 提交于 2021-02-05 11:53:37

问题


With the code below, it prints the value 'phase' one by one. I am trying to print these values as an array outside of for loop.

import math

Period = 6.2

time1 = datafile1[:,0]
magnitude1 = datafile1[:,1]
for i in range(len(time1)):
   print(i,time1[i])
   floor = math.floor((time1[i]-time1[0])/Period)
   phase = ((time1[i]-time1[0])/Period)-floor 
   print (phase)

It is printing like this:

0.002
0.003
0.004
0.005

I would like it to print like this:

[0.002, 0.003, 0.004, 0.005]

回答1:


This would be the least modification requirement path to that result

result = []

time1 = datafile1[:,0]
magnitude1 = datafile1[:,1]
for i in range(len(time1)):
   result.append(i,time1[i])
   floor = math.floor((time1[i]-time1[0])/Period)
   phase = ((time1[i]-time1[0])/Period)-floor 
   result.append(phase)

print(result)



回答2:


Here I've made it so instead of printing your results, you append them to a list, then print out the full list.

import math

Period = 6.2

time1 = datafile1[:,0]
magnitude1 = datafile1[:,1]

my_list = []
for i in range(len(time1)):
   my_list.append(i,time1[i])
   floor = math.floor((time1[i]-time1[0])/Period)
   phase = ((time1[i]-time1[0])/Period)-floor 
   my_list.append(phase)

print(my_list)



回答3:


You can do

import math

Period = 6.2

time1 = datafile1[:,0]
magnitude1 = datafile1[:,1]
list_to_print = []
for i in range(len(time1)):
   print(i,time1[i])
   floor = math.floor((time1[i]-time1[0])/Period)
   phase = ((time1[i]-time1[0])/Period)-floor
   list_to_print.append(phase)
print (list_to_print)


来源:https://stackoverflow.com/questions/52509500/printing-list-of-numbers-as-an-array-from-for-loop-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!