簡體   English   中英

Python:從一個源生成兩個互斥的數組

[英]Python: Generate two mutually-exclusive arrays from one source

我有一個內容來源,我將小麥與谷殼分開。 我想要一份箔條的記錄,以便可以目視檢查。 問題是,小麥 + 谷殼應該等於總內容長度,但事實並非如此。 代碼如下:

for report_file in REPORT_FILES:
    with open(report_file, "r+") as filey:
        content_lines = filey.read().split("\n")

    lines = [x for x in content_lines if not any(header in x for header in REPORTS[report_type]["headers"])]    
    trash = [x for x in content_lines if not any(line in x for line in lines)]

此代碼產生 {lines} 和 {trash},但 len(trash) 為 0。我也試過:

lines = [x for x in content_lines if not any (header in x for header in REPORTS[report_type]["headers"])]
trash = [x for x in content_lines if any(header in x for header in REPORTS[report_type]["headers"])]

但是 len(lines) + len(trash) 大於 len(content_lines)。

對於trash您可以獲取content_lines中不在lines 在代碼中:

trash [x for x in content_lines if x not in lines]

沒有必要讓它變得比這更復雜。

提示:您可以更換

content_lines = filey.read().split("\n")

content_lines = filey.readlines()

答案:Code-Apprentice 的答案,以及我在問題陳述中的第二個解決方案是正確的。 驗證方法很奇怪:在 bash 中使用wc -l時,它計算“\\n”字符,但不計算“\\r”。 我引用的報告以尾隨的“\\r”結尾,而不總是“\\r\\n”。

暫無
暫無

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

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