2016-10-16 5 views
0

for 루프에서 미정의 목록에 어떻게 추가합니까? 목적은 각 줄을 '-'로 먼저 자르는 것입니다. 그런 다음이 슬라이스를 크기가 지정되지 않은 배열에 추가하고 싶습니다. 나는 다음과 같은 코드를 가지고 있고 이것이 얼마나 간단한 지 모발을 잃어 버리고있다!for 루프에서 목록에 추가 (텍스트 파일 읽기)

텍스트 파일의 각 행은 다음과 같습니다 2014-06-13,42.7, -73.8,27

프로그램 지금까지 :

f = open('Lightning.txt') 

lightning =list() 

for templine in f: 

    if not templine.startswith('2014'): continue 

    templine = templine.rstrip('-') 

    line = templine.split() 

    print line[2] 

지역 사회 감사,

+0

는 u는 당신이하고자 우리에게 정확한 출력을 표시 할 수 있습니다 '2014-06-13,42.7, -73.8,27' 입력을 받고 싶습니까? – Nf4r

+0

나는 나가고 싶습니다 : (2014-04-10 : 27 번개가 기록되었습니다.) – bigdz23

답변

0

형식화 된 문자열의 목록을 얻으려면 다음과 같이하십시오.

f = open('Lightning.txt') 
lightning =list() 
for templine in f: 
    if not templine.startswith('2014'): continue 
    # We are splitting the line by ',' to get [2014-06-13, 42.7,-73.8, 27] 
    templine = templine.split(',') 
    # After splitting is done, we know that at the 1st place is the date, 
    # and at the last one is the number of video recordings. 

    #Here we asign the first item to "data" and the last one to "num_of_strikes" 
    date, num_of_strikes = templine[0], templine[-1] 
    # After that is done, we create the output string with placeholders 
    # {data} and {num} waiting for data to be passed 
    output = '{date} : {num} lightning strikes were recorded.' 
    # Here we are appending the formated string, passing our data to placeholders 
    # And yes, they work like a dictionary, so u can write (key = value) 
    lightning.append(output.format(date= date, num= num_of_strikes)) 
+0

날짜, num_of_strikes = templine [0], templine [-1] 출력 = '{날짜} : {num} 번개 기록했다. lightning.append (output.format (date = date, num = num_of_strikes)) – bigdz23

+0

이 과정을 설명해 주시겠습니까? 나는 이것을 크게 감사 할 것이다! – bigdz23

+0

완료. 의견을 읽고, 나는 그것이 도움이되기를 바랍니다. – Nf4r

0

이것은 csv LIB위한 이상적인 작업입니다 :

import csv 

with open('Lightning.txt') as f: 
    data = [] 
    # unpack the elements from each line/row 
    for dte, _, _, i in csv.reader(f): 
     # if the date starts with 2014, add the date string and the last element i 
     if dte.startswith('2014'): 
      data.append((dte, i)) 

모든 목록 빌려 사용하여 수행 할 수 있습니다 :

import csv 

with open('Lightning.txt') as f: 
    data = [(dte, i) for dte, _, _, i in csv.reader(f) if dte.startswith('2014')]