Home > Software engineering >  How can I convert a list of a list of a list to a string?
How can I convert a list of a list of a list to a string?

Time:09-27

How could I go about converting, this nested list to string form? All the code I currently have is how to get a list of a list.

food = [['Noodles', ['Pho']], ['Rice', ['Paella']]] 
list = [' '.join(lst) for lst in food]

This is code gives the error: TypeError: sequence item 1: expected str instance, list found

The output I am looking for is: "Noodles Pho,Rice Paella"

I would love any help on this, as I have been trying to find a appropriate solution for a while and have been unable to.

CodePudding user response:

It's not clear what do you want to generate - coma separated string or list. Solution is simple - iterate over food, take first element of inner list and iterate over second joining every element to first element.

food = [['Noodles', ['Pho']], ['Rice', ['Paella']]] 

result_list = [a   " "   b for a, l in food for b in l]
result_str = ",".join(a   " "   b for a, l in food for b in l)

Output:

# result_list
['Noodles Pho', 'Rice Paella']
# result_str
'Noodles Pho,Rice Paella'

You can help my country, check my profile info.

CodePudding user response:

If the format is always List[Tuple[str, List[str]]] you can do this :

food = [['Noodles', ['Pho']], ['Rice', ['Paella']]]
list_ = ', '.join([' '.join((lst[0], *lst[1])) for lst in food])
print(list_) # 'Noodles Pho, Rice Paella'

But careful, don't use the Python keyword list or you can't reuse it later in your program.

  • Related