Hadij
Hadij

Reputation: 4600

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

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 list of strings as:

B = [['ABC'],['AB']]

OR,

B = ['ABC','AB']

I tried using ''.join(A) and ''.join(str(v) for v in A) but they didn't work.

This is the error I got:

TypeError: sequence item 0: expected str instance, list found

Upvotes: 2

Views: 7651

Answers (4)

Gediz GÜRSU
Gediz GÜRSU

Reputation: 636

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

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

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.

Upvotes: 9

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

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

Output:

[['ABC'], ['AB']]

Upvotes: 2

eagle
eagle

Reputation: 890

Simple

map(''.join, A)

['ABC', 'AB']

Upvotes: 5

Related Questions