【问题标题】:Appending to a list from a for loop (to read a text file)从 for 循环附加到列表(以读取文本文件)
【发布时间】:2017-02-25 14:33:39
【问题描述】:

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

感谢社区,

【问题讨论】:

  • 你能告诉我们你想用2014-06-13,42.7,-73.8,27输入得到的确切输出吗?
  • 我想出去:(2014-04-10 : 记录了 27 次雷击。)

标签: python string list append slice


【解决方案1】:

如果您想获取格式化字符串的列表,请尝试类似的方法。

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

【讨论】:

  • date, num_of_strikes = templine[0], templine[-1] output = '{date} : {num} 次雷击被记录。' Lightning.append(output.format(date= date, num= num_of_strikes))
  • 您能描述一下这个过程吗?我将不胜感激!
  • 完成。阅读 cmets,希望对您有所帮助。
  • 这样的救命稻草,我必须消化它,但我会得到它。非常感谢 Nf4r!
【解决方案2】:

这是csv 库的理想工作:

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

【讨论】:

    猜你喜欢
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    相关资源
    最近更新 更多