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

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

提交回复
热议问题