0

I have a list with this format:

lista_d = [
    ('1', '2', 1.393063105981541),
    ('1', '6', 1.450829019495749),
    ('1', '16', 1.4508291645112752),
    ('2', '1', 1.393063105981541),
    ('2', '3', 1.4508290090832596),
    ('2', '15', 1.4508291577448584),
    ('3', '2', 1.4508290090832596), 
    ('3', '4', 1.3930630800761916)
]

I need to convert this list to csv with tree columns for example

1       2      1.393063105981541

With all items in list.

I tried with this but but everything is in the first column

with open('dist.csv','w') as f:
    write = csv.writer(f)
    for i in lista_d:
        write.writerow(i)

Can anyone help with this?

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
Jose Pinto
  • 121
  • 4

2 Answers2

0

You can specify the delimiter to the csv writer:

with open('dist.csv','w') as f:
    # you can change the delimiter in the csv
    # '\t' mean tabs
    write= csv.writer(f, delimiter='\t')
    for i in lista_d:
        write.writerow(i)

dist.csv:

1   2   1.393063105981541
1   6   1.450829019495749
1   16  1.4508291645112752
2   1   1.393063105981541
2   3   1.4508290090832596
2   15  1.4508291577448584
3   2   1.4508290090832596
3   4   1.3930630800761916
Lucas
  • 6,869
  • 5
  • 29
  • 44
0

Specifying a delimiter when invoking csv.writer should solve the issue.

with open('dist.csv','w') as f:
    write = csv.writer(f, delimiter=',')
    for i in lista_d:
        write.writerow(i)
Atanu Barai
  • 115
  • 7
  • 1
    While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading. From [answer]: _"Brevity is acceptable, but fuller explanations are better."_ – Pranav Hosangadi May 17 '21 at 19:25