是否有更好的方法来完成此功能?

2024-05-19 08:11:25 发布

您现在位置:Python中文网/ 问答频道 /正文

最近,我发现了一本书,书名为“用Python自动化那些无聊的东西”。我参加了一个练习,上面说

Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.

我写了这段代码,但我相信有更好的方法。最简单的方法是什么

def list_manu(lst):
  spam[-1] = 'and '+spam[-1]
  new_spam=[] 
  x = ','.join(spam)
  return f"'{x}'"  

spam = ['apples', 'bananas', 'tofu','here','here', 'cats']
print(list_manu(spam))

Tags: andtheto方法returnvaluewithfunction
2条回答

您可以使用“and”连接最后两个元素,并使用逗号将其与前面的元素连接:

# without Oxford comma (e.g. French punctuation)
def list_manu(lst):
    return ", ".join(lst[:-2]+[" and ".join(lst[-2:])])

# with Oxford comma (uses ', and ' when size is 3+)
def list_manu(lst):
    return ", ".join(lst[:-2]+[", and "[len(lst)<3:].join(lst[-2:])])

输出:

spam = ['apples', 'bananas', 'tofu','here','here', 'cats']

list_manu(spam)   # 'apples, bananas, tofu, here, here, and cats'

# works with all list sizes
list_manu([])                            # ''
list_manu(['apple'])                     # 'apple'
list_manu(['apple','oranges'])           # 'apple and oranges'
list_manu(['apple','oranges','bananas']) # 'apple, oranges, and bananas'

这个程序负责Oxford comma-

def list_manu(spam):
   if not spam:
      return "Your list is empty!"

   elif len(spam) == 1:
      return f"'{spam[0]}'"

   elif len(spam) == 2:
      return f"'{spam[0]} and {spam[1]}'"

   else:
      body = ", ".join(map(str, spam[:-1]))
      return f"'{body}, and {spam[-1]}'"
    
spam = ['apples', 'bananas', 'tofu', 'here', 'here', 'cats']
print(list_manu(spam))

输出:

'apples, bananas, tofu, here, here, and cats'

此程序不处理牛津逗号,但它适合您指定任务的目的-

def list_manu(spam):
   if len(spam) == 1:
      return f"'{spam[0]}'"

   body = ", ".join(map(str, spam[:-1]))  
   return f"'{body}, and {spam[-1]}'"
    
spam = ['apples', 'bananas', 'tofu', 'here', 'here', 'cats']
print(list_manu(spam))

输出:

'apples, bananas, tofu, here, here, and cats'

相关问题 更多 >

    热门问题