从列表语法上正确的人类可读字符串(带有牛津逗号) [英] Grammatically correct human readable string from list (with Oxford comma)
问题描述
我想要列表的语法上正确的,人类可读的字符串表示形式.例如,列表['A', 2, None, 'B,B', 'C,C,C']
应该返回字符串A, 2, None, B,B, and C,C,C
.这个人为的例子有些必要.请注意,牛津逗号与该问题有关.
I want a grammatically correct human-readable string representation of a list. For example, the list ['A', 2, None, 'B,B', 'C,C,C']
should return the string A, 2, None, B,B, and C,C,C
. This contrived example is somewhat necessary. Note that the Oxford comma is relevant for this question.
我尝试了', '.join(seq)
,但是对于上述示例而言,这不会产生预期的结果.
I tried ', '.join(seq)
but this doesn't produce the expected result for the aforementioned example.
请注意先前存在的类似问题:
Note the preexisting similar questions:
- 如何在Python中很好地"打印列表与语法正确的人类可读字符串无关.
- Python中的语法列表联接没有
- How to print a list in Python "nicely" doesn't concern with a grammatically correct human-readable string.
- Grammatical List Join in Python is without the Oxford comma. The example and answers there are correspondingly different and they do not work for my question.
推荐答案
此功能通过处理小列表而不是大列表来工作.
This function works by handling small lists differently than larger lists.
from typing import Any, List
def readable_list(seq: List[Any]) -> str:
seq = [str(s) for s in seq]
if len(seq) < 3:
return ' and '.join(seq)
return ', '.join(seq[:-1]) + ', and ' + seq[-1]
用法示例:
readable_list([])
''
readable_list(['A'])
'A'
readable_list(['A', 2])
'A and 2'
readable_list(['A', None, 'C'])
'A, None, and C'
readable_list(['A', 'B,B', 'C,C,C'])
'A, B,B, and C,C,C'
readable_list(['A', 'B', 'C', 'D'])
'A, B, C, and D'
这篇关于从列表语法上正确的人类可读字符串(带有牛津逗号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!