簡體   English   中英

從for循環追加到列表(讀取文本文件)

[英]Appending to a list from a for loop (to read a text file)

如何從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]

謝謝社區,

如果要獲取格式字符串列表,請嘗試類似的操作。

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))

這是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))

使用list comp可以全部完成:

import csv

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM