How would you make a comma-separated string from a list of strings?

后端 未结 14 1243
北海茫月
北海茫月 2020-11-22 16:07

What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance

14条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 16:37

    My two cents. I like simpler an one-line code in python:

    >>> from itertools import imap, ifilter
    >>> l = ['a', '', 'b', 1, None]
    >>> ','.join(imap(str, ifilter(lambda x: x, l)))
    a,b,1
    >>> m = ['a', '', None]
    >>> ','.join(imap(str, ifilter(lambda x: x, m)))
    'a'
    

    It's pythonic, works for strings, numbers, None and empty string. It's short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:

    >>> ','.join(ifilter(lambda x: x, l))
    

    Also this solution doesn't create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).

提交回复
热议问题