Sorting CSV in Python

后端 未结 4 1419
暖寄归人
暖寄归人 2020-12-09 13:37

I assumed sorting a CSV file on multiple text/numeric fields using Python would be a problem that was already solved. But I can\'t find any example code anywhere, except for

4条回答
  •  無奈伤痛
    2020-12-09 14:38

    Here's the convert() that's missing from Robert's fix of Alex's answer:

    >>> def convert(convert_funcs, seq):
    ...    return [
    ...        item if func is None else func(item)
    ...        for func, item in zip(convert_funcs, seq)
    ...        ]
    ...
    >>> convert(
    ...     (None, float, lambda x: x.strip().lower()),
    ...     [" text ", "123.45", " TEXT "]
    ...     )
    [' text ', 123.45, 'text']
    >>>
    

    I've changed the name of the first arg to highlight that the per-columns function can do what you need, not merely type-coercion. None is used to indicate no conversion.

提交回复
热议问题