How to join nested list of strings and get the result as new list of string?

后端 未结 4 1839
忘了有多久
忘了有多久 2021-01-07 02:24

I am having nested list of strings as:

A = [[\"A\",\"B\",\"C\"],[\"A\",\"B\"]]

I am trying to join the strings in sublist to get a single l

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-07 02:47

    You can use ''.join with map here to achieve this as:

    >>> A = [["A","B","C"],["A","B"]]
    >>> list(map(''.join, A))
    ['ABC', 'AB']
    
    # In Python 3.x, `map` returns a generator object.
    # So explicitly type-casting it to `list`. You don't 
    # need to type-cast it to `list` in Python 2.x
    

    OR you may use it with list comprehension to get the desired result as:

    >>> [''.join(x) for x in A]
    ['ABC', 'AB']
    

    For getting the results as [['ABC'], ['AB']], you need to wrap the resultant string within another list as:

    >>> [[''.join(x)] for x in A]
    [['ABC'], ['AB']]
    
    ## Dirty one using map (only for illustration, please use *list comprehension*)
    # >>> list(map(lambda x: [''.join(x)], A))
    # [['ABC'], ['AB']]
    

    Issue with your code: In your case ''.join(A) didn't worked because A is a nested list, but ''.join(A) tried to join together all the elements present in A treating them as string. And that's the cause for your error "expected str instance, list found". Instead, you need to pass each sublist to your ''.join(..) call. This can be achieved with map and list comprehension as illustrated above.

提交回复
热议问题