【问题标题】:Reconciling an array slicer协调数组切片器
【发布时间】:2020-01-30 18:36:46
【问题描述】:

我已经构建了一个函数来从文本条目中删除无关的垃圾。它使用数组切片器。我现在需要协调已被我的清理功能删除的行,以便所有lines_lost + lines_kept = 总行。源码如下:

def header_cleanup(entry_chunk):
    # Removes duplicate headers due to page-continuations
    entry_chunk = entry_chunk.replace("\r\n\r\n","\r\n")
    header = lines[1:5]
    lines[:] = [x for x in lines if not any(header == x for header in headers)]
    lines = headers + lines
    return("\n".join(lines))

如何计算切片/突变后未显示在行中的行,即:

original_length = len(lines)
lines = lines.remove_garbage
garbage = lines.garbage_only_plz
if len(lines) + len(garbage) == original_length:
    print("Good!")
else:
    print("Bad!  ;(")

最终的答案是这样的:

def header_cleanup(entry_chunk):
    lines = entry_chunk.replace("\r\n\r\n","\r\n")
    line_length = len(lines)
    headers = lines[1:5]
    saved_lines = []
    bad_lines = []
    saved_lines[:] = [x for x in lines if not any(header == x for header in headers)]
    bad_lines[:] = [x for x in lines if any(header == x for header in headers)]
    total_lines = len(saved_lines) + len(bad_lines)
    if total_lines == line_length:
        print("Yay!")
    else:
        print("Boo.")
        print(f"{rando_trace_info}")
        sys.exit()
    final_lines = headers + saved_lines
    return("\n".join(final_lines))

Okokokokok - 我知道你在想:这是多余的,但它是必需的。在解决方案后打开编辑以获取更多pythonic。感谢您的考虑。

【问题讨论】:

    标签: python list slicers


    【解决方案1】:

    不要重复使用 lines 变量,使用不同的变量,这样你就可以从原始行中取出垃圾。

    clean_lines = remove_garbage(lines)
    garbage = garbage_only(lines)
    if len(clean_lines) + len(garbage) == len(lines):
        print("Good!")
    else:
        print("Bad!")
    

    您可能希望有一个同时返回两者的函数:

    clean_lines, garbage = filter_garbage(lines)
    

    【讨论】:

    • 罗杰。但是,如果我想构建一个与 clean_lines 完全相反的垃圾切片,如果我说以下内容,在所有情况下都是准确的:lines[:] = [x for x in lines if not any(header == x for header in headers)] 垃圾[:] = [x for x in lines if any(header == x for header in headers)]
    • 您可以将 any() 调用简化为 if x not in headers
    猜你喜欢
    • 2012-11-10
    • 1970-01-01
    • 2021-09-04
    • 2012-02-23
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    相关资源
    最近更新 更多