簡體   English   中英

Python:如何僅將一個變量傳遞給lambda函數?

[英]Python: How to pass in only one variable into a lambda function?

我的代碼是逐行讀取文本文件。 然后,將每一行的所有空白都修剪為一個空格字符,並根據其是否與模式匹配,將其寫入到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中(源文件名)文件“ model_dev_txt_to_csv.py”,進程23中的行process_line(行,lambda:write_csv(m,行),lambda: write_csv(u,line))文件“ model_dev_txt_to_csv.py”,第12行,如果pattern.match(line)則返回成功(line = row),否則process(line = row)否則失敗(line = row)TypeError:()得到了意外的關鍵字參數'線'

以下是我當前的代碼:

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)

Lambda表達式在Python中的語法為:

lambda [list of arguments]: <expression>

在您的代碼中,您沒有為lambda定義任何參數。 您需要在:字符前添加一個名為line的參數,以使代碼正常工作:

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

暫無
暫無

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

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