将数组输入到For循环中,但只能将一个数组浮出

时间:2017-10-06 18:32:59

标签: python python-2.7 loops for-loop floating-point

我正在尝试向下舍入数组longYearDig中的值,然后将值从浮点数转换为整数。但是,当我输入一个包含10个值longYearDig的数组时,我只得到一个浮出pointyearDig

我投入的内容: longYearDig = [ 98.32428472 98.32433235 98.32445675 98.32451913 98.32451913 98.32458141 98.32464367 98.32489267 98.32501715 98.32545376]

我想要的是什么:

  

yearDig = [98,98,98,98,98,98,98,98,98,98]

     

year = [1998,1998,1998,1998,1998,1998,1998,1998,1998,1998]

代码:

import numpy as np
import math
import datetime

filename = 'zarya2.txt'
a = np.genfromtxt(filename)

evens = []
odds = []
for i in range(20):   #2913*2
    if np.mod(i,2) == 0:
        evens.append(a[i,:])
    else:
        odds.append(a[i,:])

oddsArray = np.asarray(odds)
evensArray = np.asarray(evens)

'Four Digit Year'
longYearDig = evensArray[:,3] /1000
print 'longYearDig', longYearDig

for i in range(len(longYearDig)):
    pointyearDig = math.floor(longYearDig[i])
print 'pointyearDig', pointyearDig


for i in range(len(pointyearDig)):
    yearDig = int(pointyearDig[i])
print 'yearDig', yearDig


#yearDigit = 98

for i in range(len(yearDig)):
    if yearDig > 17:
        year = yearDig + 1900
    else: 
        year = yearDig + 2000

print('year', year)

输出:

  

longYearDig [98.32428472 98.32433235 98.32445675 98.32451913   98.32451913     98.32458141 98.32464367 98.32489267 98.32501715 98.32545376]

     

pointyearDig 98.0

     

文件" / Users / mrmenzel / Desktop / orbits / zaryaISSdataTLE",第93行,in          对于范围内的我(len(pointyearDig)):

     

TypeError:类型为' float'的对象没有len()

1 个答案:

答案 0 :(得分:1)

只需使用numpy的地板功能

longYearDig = evensArray[:,3] /1000
print 'longYearDig', longYearDig
pointyearDig =np.floor(longYearDig)

它会将floor函数应用于每个元素并返回所需的数组。 然后你可以这样结束:

year = []
for i in range(len(pointyearDig)):
    if pointyearDig[i] > 17:
        year.append(int(pointyearDig[i]) + 1900)
    else: 
        year.append(int(pointyearDig[i]) + 2000)

另一种解决方案:

你可以使用python中的//运算符,它为你提供了分区的底层部分。您可以压缩代码然后:

longYearDig = np.array(evensArray[:,3]) // 1000
year = []
for i in range(len(longYearDig )):
    if longYearDig[i] > 17:
        year.append(longYearDig [i] + 1900)
    else: 
        year.append(longYearDig [i] + 2000)