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

后端 未结 4 1834
忘了有多久
忘了有多久 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:30

    Simple

    map(''.join, A)
    
    ['ABC', 'AB']
    
    0 讨论(0)
  • 2021-01-07 02:41

    I wrote these and found them very useful in my case, you can adapt them to your needs ...

    First one is to flatten nested list but not loose degree of nestedness by using tabs '\t'. Second one clears tabs and empty lines'.

    def nested2str(s,d):
        isNested=False;
        for i in s:
            if type(i)==list:
                isNested=True;
    
        if isNested==False:
            t=''
            for i in s:
                t=t+'\t'*d+i+'\n'
            return t
    
        for i in range(len(s)):
            if type(s[i])==list:
                s[i]=nested2str(s[i],d+1)
    
        t=''
        for i in s:
            t=t+'\t'*d+i+'\n'
        return t
    
    def clearStr(s):
        for i in range(10):
            s=s.replace('\n\n','\n')
            return s.replace('\n\n','\n').replace('\t','')
    

    I have a nested variable :

    print(temp)                                                                                                              
    ['gediz i5\n', 'Wan İp', 'Lan Ip', ['Model name:          Intel(R) Core(TM) i5-3570K CPU @ 3.40GHz'], ['CPU(s):              4'], 'RAM: 15.6GB', ['01:00.0 VGA compatible controller: NVIDIA Corporation TU104 [GeForce RTX 2070 SUPER] (rev a1)'], ['disk TOSHIBA-TR200    447,1G', 'disk KINGSTON SHFS37A 111,8G', 'disk SAMSUNG HD103SJ  931,5G']]
    

    It modifies temp, if you only use nested2str:

    print(nested2str(temp,0)))
    gediz i5
    
    Wan ip
    Lan ip
        Model name:          Intel(R) Core(TM) i5-3570K CPU @ 3.40GHz
    
        CPU(s):              4
    
    RAM: 15.6GB
        01:00.0 VGA compatible controller: NVIDIA Corporation TU104 [GeForce RTX 2070 SUPER] (rev a1)
    
        disk TOSHIBA-TR200    447,1G
        disk KINGSTON SHFS37A 111,8G
        disk SAMSUNG HD103SJ  931,5G
    

    If you use both:

    print(clearStr(nested2str(temp,0)))                                                                                      
    gediz i5
    Wan Ip
    Lan Ip
    Model name:          Intel(R) Core(TM) i5-3570K CPU @ 3.40GHz
    CPU(s):              4
    RAM: 15.6GB
    01:00.0 VGA compatible controller: NVIDIA Corporation TU104 [GeForce RTX 2070 SUPER] (rev a1)
    disk TOSHIBA-TR200    447,1G
    disk KINGSTON SHFS37A 111,8G
    disk SAMSUNG HD103SJ  931,5G
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 02:47

    You can try this:

    A = [["A","B","C"],["A","B"]]
    new_a = [[''.join(b)] for b in A]
    

    Output:

    [['ABC'], ['AB']]
    
    0 讨论(0)
提交回复
热议问题