Home > Software engineering >  Concatenate the items of a list into one list item
Concatenate the items of a list into one list item

Time:10-26

I have a list called 'grid' that contains 12 other lists of letters. Each is Stored as a single string character. I want to concatenate these lists so each list contains only one string. Strange I know but this is the best format for this data.

I've tried a number of different ways to alter this list so that each letter is concatenated to one string but still separated into 12 lists as each list is a row. Any help would be appreciated.

The easiest way to explain is to show the current and desired outcome.

Current Result Current Result

Desired Result

Desired Result

CodePudding user response:

Try looping and concatenating, replace a with your list.

def ptest():
    c = 0
    s = ""
    a = [['a','b'],['c', 'd']]
    for i in a:
        s = s.join(i)
        a[c] = [s]
        c = c 1

    print a

ptest()

CodePudding user response:

Does this work:

a = [['a','b'],['c', 'd'], ['e', 'f']]
out = []
for item in a:
    out.append(["".join(item)])
print (out)

Output:

[['ab'], ['cd'], ['ef']]
  • Related