python - 列表的自定义字符串表示取决于项目数 (Python)

标签 python python-3.x list

我需要根据它有多少项目来打印出不同的列表:

例如:

  • 对于没有项目,即 [] 应该输出 {}
  • 对于 1 个项目,即 ["Cat"] 应该输出 {Cat}
  • 对于 2 个项目,即 ["Cat", "Dog"] 应该输出 {Cat and Dog}
  • 对于 3 个或更多项目,即 ["Cat", "Dog", "Rabbit", "Lion"] 应该输出 {Cat, Dog, Rabbit and Lion}

我目前正在用一堆 if 语句做这样的事情:

def customRepresentation(arr):
  if len(arr) == 0:
    return "{}"
  elif len(arr) == 1:
    return "{" + arr[0] + "}"
  elif len(arr) == 2:
    return "{" + arr[0] + " and " + arr[0] + "}"
  else:  
    # Not sure how to deal with the case of 3 or more items

是否有更 pythonic 的方法来做到这一点?

最佳答案

假设单词本身永远不会包含逗号。您可以改用 join replace 在一行中处理所有案例:

>>> def custom_representation(l):
...   return "{%s}" % " and ".join(l).replace(" and ", ", ", len(l) - 2)
... 
>>> for case in [], ["Cat"], ["Cat", "Dog"], ["Cat", "Dog", "Rabbit", "Lion"]:
...   print(custom_representation(case))
... 
{}
{Cat}
{Cat and Dog}
{Cat, Dog, Rabbit and Lion} 

关于python - 列表的自定义字符串表示取决于项目数 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616102/

相关文章:

python - 使用 html5 视频标签时视频无法在 safari 中播放

python - 我可以在 Python 中使用 geopy 获得海拔高度吗? (带经度/纬度)

python - 查找列表的 x 最小值的索引

python-3.x - 与逻辑回归、SVM 和带有交叉验证网格搜索的朴素贝叶斯相比,随机森林分类器的性能是否明显不佳?

c# - 从同一个列表中选择相似的元素

python - Django-如何映射用户之间发送的消息

python - Pandas - 在整个数据框中查找特定值

python - 使用Scrapy爬取MIT OCW网站,但输出为空

r - 列表列表中向量的平均值

Python 连接列表