从for循环追加到列表(读取文本文件)

时间:2016-10-16 16:03:03

标签: python string list append slice

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

谢谢社区,

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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))

使用list comp可以完成所有工作:

import csv

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