Python 列表中语法正确的人类可读字符串(带牛津逗号)

Python 列表中语法正确的人类可读字符串(带牛津逗号),python,list,human-readable,Python,List,Human Readable,我想要一个语法正确、可读的列表字符串表示形式。例如,列表['A',2,None',B,B',C,C']应该返回字符串A,2,None,B,B和C,C,C。这个人为的例子有些必要。请注意,此选项与此问题相关 我尝试了,'.join(seq),但这并没有产生上述示例的预期结果 请注意先前存在的类似问题: 与语法正确的人类可读字符串无关 这是没有的。那里的例子和答案相应地不同,它们不适用于我的问题 此功能的工作原理是处理小列表与处理大列表不同 from typing import Any, List

我想要一个语法正确、可读的列表字符串表示形式。例如,列表
['A',2,None',B,B',C,C']
应该返回字符串
A,2,None,B,B和C,C,C
。这个人为的例子有些必要。请注意,此选项与此问题相关

我尝试了
,'.join(seq)
,但这并没有产生上述示例的预期结果

请注意先前存在的类似问题:

  • 与语法正确的人类可读字符串无关
  • 这是没有的。那里的例子和答案相应地不同,它们不适用于我的问题

此功能的工作原理是处理小列表与处理大列表不同

from typing import Any, List

def readable_list(seq: List[Any]) -> str:
    """Return a grammatically correct human readable string (with an Oxford comma)."""
    # Ref: https://stackoverflow.com/a/53981846/
    seq = [str(s) for s in seq]
    if len(seq) < 3:
        return ' and '.join(seq)
    return ', '.join(seq[:-1]) + ', and ' + seq[-1]

您还可以使用解包来获得稍微干净的解决方案:

def readable_list(_s):
  if len(_s) < 3:
    return ' and '.join(map(str, _s))
  *a, b = _s
  return f"{', '.join(map(str, a))}, and {b}"
输出:

['', 'A', 'A and 2', 'A, None, and C', 'A, B,B, and C,C,C', 'A, B, C, and D']

我变得很固执,我真的很想找出一个线性解决方案

"{} and {}".format(seq[0], seq[1]) if len(seq)==2 else ', '.join([str(x) if (y < len(seq)-1 or len(seq)<=1) else "and {}".format(str(x)) for x, y in zip(seq, range(len(seq)))])
“{}和{}”.format(seq[0],seq[1])如果len(seq)==2 else','.join([str(x)如果(y
from typing import List

def list_items_in_english(l: List[str], oxford_comma: bool = True) -> str:
    """
    Produce a list of the items formatted as they would be in an English sentence.
    So one item returns just the item, passing two items returns "item1 and item2" and
    three returns "item1, item2, and item3" with an optional Oxford comma.
    """
    return ", ".join(l[:-2] + [((oxford_comma and len(l) != 2) * ',' + " and ").join(l[-2:])])

哈?你为什么这么说?我想命令做了我认为OP想做的事。对不起,我误解了,我收回了旗帜。一切都很好:)@GiacomoCasoni Given
seq=[1,2]
,返回值在语法上应该是
'1和2'
,但此答案返回的是
'1和2'
,这是不正确的。此答案应该是固定的(同时保持其原始性)或者被删除。被修改是更好的。哦,我一定误解了牛津逗号是什么。让我看看是否可以修改它
"{} and {}".format(seq[0], seq[1]) if len(seq)==2 else ', '.join([str(x) if (y < len(seq)-1 or len(seq)<=1) else "and {}".format(str(x)) for x, y in zip(seq, range(len(seq)))])
from typing import List

def list_items_in_english(l: List[str], oxford_comma: bool = True) -> str:
    """
    Produce a list of the items formatted as they would be in an English sentence.
    So one item returns just the item, passing two items returns "item1 and item2" and
    three returns "item1, item2, and item3" with an optional Oxford comma.
    """
    return ", ".join(l[:-2] + [((oxford_comma and len(l) != 2) * ',' + " and ").join(l[-2:])])