Python:如何只将一个变量传入lambda函数?

时间:2015-11-06 10:48:03

标签: python lambda

我的代码逐行读取文本文件。然后将每个行的所有空格修剪为一个空格字符,并根据它是否与模式匹配,然后将其写入matched_data_file或unmatched_data_file。我必须在这个特定的例子中使用lambda。我认为错误在于以下行,但我并非100%确定:

success(line=row) if pattern.match(line) else failure(line=row)

非常感谢任何帮助,提前谢谢!

我收到以下错误消息:

  

回溯(最近一次呼叫最后):文件" model_dev_txt_to_csv.py",   第26行,在       process(source_filename)File" model_dev_txt_to_csv.py",第23行,正在处理中       process_line(line,lambda:write_csv(m,line),lambda:write_csv(u,line))File" model_dev_txt_to_csv.py",第12行,in   process_line       返回成功(line = row)如果pattern.match(line)else失败(line = row)TypeError :()得到了一个意外的关键字   争论' line'

以下是我目前的代码:

import re
import csv

pattern = re.compile("([0-9]+) +([0-9\.-]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+)")
source_filename = "track_param_hist.txt"
matched_data_file = "good_hist_csv.csv"
unmatched_data_file = "bad_hist_csv.csv"

def process_line(line, success, failure):
    # Make sure all whitespace is reduced to one space character
    row = (' '.join(line.split())).split(' ')
    success(line=row) if pattern.match(line) else failure(line=row)

def write_csv(file, line):
    csv.writer(file).writerow(line)

def process(source):
    print("Script for splitting text file into two separate csvs...")
    with open(matched_data_file, 'w') as m:
        with open(unmatched_data_file, 'w') as u:
            with open(source) as f:
                for line in f:
                    process_line(line, lambda: write_csv(m, line), lambda: write_csv(u, line))

if __name__ == "__main__":
    process(source_filename)

1 个答案:

答案 0 :(得分:2)

Python中的Lambda表达式syntax是:

lambda [list of arguments]: <expression>

在您的代码中,您没有为lambdas定义任何参数。您需要在line字符前添加名为:的参数才能使代码正常工作:

lambda line: write_csv(m, line), lambda line: write_csv(u, line)