How to join list in Python but make the last separator different?

后端 未结 8 1662
一向
一向 2020-11-28 15:28

I\'m trying to turn a list into separated strings joined with an ampersand if there are only two items, or commas and an ampersand between the last two e.g.

         


        
8条回答
  •  清歌不尽
    2020-11-28 16:06

    ('{}, '*(len(authors)-2) + '{} & '*(len(authors)>1) + '{}').format(*authors)
    

    This solution can handle a list of authors of length > 0, though it can be modified to handle 0-length lists as well. The idea is to first create a format string that we can format by unpacking list. This solution avoids slicing the list so it should be fairly efficient for large lists of authors.

    First we concatenate '{}, ' for every additional author beyond two authors. Then we concatenate '{} & ' if there are two or more authors. Finally we append '{}' for the last author, but this subexpression can be '{}'*(len(authors)>0) instead if we wish to be able to handle an empty list of authors. Finally, we format our completed string by unpacking the elements of the list using the * unpacking syntax.

    If you don't need a one-liner, here is the code in an efficient function form.

    def format_authors(authors):
        n = len(authors)
        if n > 1:
            return ('{}, '*(n-2) + '{} & {}').format(*authors)
        elif n > 0:
            return authors[0]
        else:
            return ''
    

    This can handle a list of authors of any length.

提交回复
热议问题