Home > Software design >  Convert a list within a list to a string
Convert a list within a list to a string

Time:10-05

Let's assume I have the following list: my_lst = [['a', ['b']], ['a1', ['b1']]]. I want to convert it to "a b, a1 b1".

my_lst = [['a', ['b']], ['a1', ['b1']]]
for i in my_lst:
    first_idx = i[0]
    second_idx = i[1][0]
    print(f"{first_idx} {second_idx}", end=",")

My code gives a b,a1 b1,. I don't understand how to remove the comma from the end.

CodePudding user response:

Given

my_lst = [['a', ['b']], ['a1', ['b1', 'b2', 'b3']]]

This

[ [h, *t] for h, t in my_lst ]

gives you

[['a', 'b'], ['a1', 'b1', 'b2', 'b3']]

this

[ ' '.join([h, *t]) for h, t in my_lst ]

returns

['a b', 'a1 b1 b2 b3']

and finally this

', '.join( ' '.join([h, *t]) for h, t in my_lst )

returns

'a b, a1 b1 b2 b3'

which appears to be what you're looking for

CodePudding user response:

Don't print each string in the loop, use join() to combine them with comma separators.

result = ','.join(f"{i[0]} {' '.join(i[1])}" for i in my_lst)
print(result)
  • Related