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

后端 未结 14 1023
北海茫月
北海茫月 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:40

    @Peter Hoffmann

    Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.

    >>> l = [1, "foo", 4 ,"bar"]
    >>> ",".join(str(bit) for bit in l)
    '1,foo,4,bar' 
    
    0 讨论(0)
  • 2020-11-22 16:40

    Here is an example with list

    >>> myList = [['Apple'],['Orange']]
    >>> myList = ','.join(map(str, [i[0] for i in myList])) 
    >>> print "Output:", myList
    Output: Apple,Orange
    

    More Accurate:-

    >>> myList = [['Apple'],['Orange']]
    >>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) 
    >>> print "Output:", myList
    Output: Apple,Orange
    

    Example 2:-

    myList = ['Apple','Orange']
    myList = ','.join(map(str, myList)) 
    print "Output:", myList
    Output: Apple,Orange
    
    0 讨论(0)
提交回复
热议问题