1

I would like to write a list of lists : k = [['1','a'],['2','b'],['3','c']] - to a cell in a Python excel sheet.

My code:

workbook = xlsxwriter.Workbook('names.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Generic Name')

I have tried: worksheet.write_row('B1', allmajor) which causes the contents the list k to be written in separate cells (B1, C1, D1..).

Doing: worksheet.write('B1', ','.join(k)) causes the cotnents of cell B1 to have strings like - '1','a','2','b','3','c'

Is there any way in which I can write a list to a cell such that cell B1 looks like [['1','a'],['2','b'],['3','c']]? Is there any other module in Python that can facilitate this?

2 Answers 2

2

You can use the built-in function repr which gives a string representation of the list object:

worksheet.write('B1', repr(k))

At python prompt you can see how it works:

>>> k = [['1','a'],['2','b'],['3','c']]
>>> k
[['1', 'a'], ['2', 'b'], ['3', 'c']]
>>> repr(k)
"[['1', 'a'], ['2', 'b'], ['3', 'c']]"
>>> print(repr(k))
[['1', 'a'], ['2', 'b'], ['3', 'c']]

In the case of your simple list structure, you could just cast it to a string as well like str(k) but repr is probably better for this case.

Sign up to request clarification or add additional context in comments.

Comments

1

You can take care of this by converting your list of list to string. For example

>>import pandas as pd
>>list1=[['1','a'],['2','b'],['3','c']]
>>list2=[['4','a'],['5','b'],['6','c']]
>>df=pd.DataFrame({'a':[str(list1), str(list2)]]})

Now when you save it in a comma separated format,each element will be treated as a string. When you read this back from file, you can use ast to convert it back into a list of lists.

>>import ast
>>[ast.literal_eval(i) for i in df['a']]

Hope this answers your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.