hlku2334
hlku2334

Reputation: 63

Printing list of numbers as an array from for loop Python

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]

Upvotes: 0

Views: 6113

Answers (3)

Daveedo
Daveedo

Reputation: 172

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)

Upvotes: 0

Matt
Matt

Reputation: 1632

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)

Upvotes: 0

vash_the_stampede
vash_the_stampede

Reputation: 4606

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)

Upvotes: 2

Related Questions