循环访问列表中的两个输出字符串

时间:2019-01-23 08:00:03

标签: arrays python-3.x string for-loop enumerate

import pytaf

def METARextraction():

    with open('metars_CYMX.txt') as f:
        content = f.readlines()
        # you may also want to remove whitespace characters like `\n` at the end of each line
        content = [x.strip() for x in content] 
        #print(content)

    time_array = ["","",""] * len(content)

    for values in content: 
        print("A")
        """ 
        Function built to extract time from pytaf using any METARs  
        Extracts - 'origin_minutes',' origin_hours', 'orgin_date'
        """
        timebag0 =[]
        timebag1 =[]
        timebag2 =[]
        taf = pytaf.TAF(values)
        taf_header = taf._taf_header
        timebag1=taf_header['origin_minutes']
        timebag2=taf_header['origin_hours'])
        timebag3=taf_header['origin_date']
        for k in range(0,len(content)):
            time_array[k,timebag1]
            time_array[k,timebag2]
            time_array[k,timebag3]

    return(time_array)

print(METARextraction())


metars_CYMX.txt file 

CYMX 090000Z 02004KT 340V060 15SM OVC014 07/06 A3027 RMK SC8 SLP255
CYMX 090100Z 06005KT 010V080 15SM OVC010 07/06 A3026 RMK SC8 SLP250
CYMX 090200Z VRB02KT 15SM OVC008 07/06 A3024 RMK ST8 PRESFR SLP244
CYMX 090300Z VRB02KT 15SM OVC006 07/07 A3023 RMK ST8 SLP240
CYMX 090344Z 04003KT 010V090 10SM TS OVC005 07/06 A3022 RMK ST8 OCNL LTGIC E 
CVCTV CLD EMBDD SLP238
CYMX 090347Z 04003KT 010V090 10SM -TSRA BKN005 OVC012CB 07/07 A3022 RMK SF6CB2 OCNL LTGIC E VIS SW-NW 5 SLP237

该函数应该做的是每次取出,并将其分为日,小时和分钟

因为文本文件中有6次迭代

我需要一个数组time_array

['09','09','09','09','09','09']
['00','01','02','03','03','03']
['00','00','00','00','44','47']

或我要尝试的组合

我知道如何在MATLAB中使用to循环在i和k上进行迭代

我认为我可能需要使用枚举

获取错误

Traceback (most recent call last):
File "main.py", line 34, in <module>
print(METARextraction())
File "main.py", line 28, in METARextraction
time_array[k,timebag1]
TypeError: list indices must be integers or slices, not tuple

1 个答案:

答案 0 :(得分:1)

我对您的代码进行了一些更改,请检查以下内容,让我知道它是否有效

import pytaf

def METARextraction():

with open('metars_CYMX.txt') as f:
    content = f.readlines()
    # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    print(content)

hours_val = []
minutes_val =[]
date_val =[]
time_array = [date_val, minutes_val, hours_val]

for values in content:
    """ 
    Function built to extract time from pytaf using any METARs  
    Extracts - 'origin_minutes',' origin_hours', 'orgin_date'
    """
    taf = pytaf.TAF(values)
    taf_header = taf._taf_header
    hours_val.append(taf_header['origin_minutes'])
    minutes_val.append(taf_header['origin_hours'])
    date_val.append(taf_header['origin_date'])

return(time_array)

print(METARextraction())

输出:

[['09', '09', '09', '09', '09', '09'],
 ['00', '01', '02', '03', '03', '03'],
 ['00', '00', '00', '00', '44', '47']]