Eva Rolin
Eva Rolin

Reputation: 41

How to extract informations of a list of tuples and how to write more than one information per line?

I'm wondering how I can resolve this problem... My input is :[(18.41870765673129, 9.511001141278493), (17.013801776758395, 14.63476877634968)] and I would like write with informations of tuple, one file like that:

18.41870765673129, 9.511001141278493
17.013801776758395, 14.63476877634968

I would like have two informations per line. My script:

def write(filename, l):
    with open(filename,"w") as file:
         for i in range(len(l)):
             for j in l[i]:
                 s = str(j)
                 file.write(s)

But my script doesn't work because the ouptut is:

18.418707656731299.51100114127849317.01380177675839514.63476877634968

Thank you!!!

Upvotes: 1

Views: 49

Answers (3)

Hemang Vyas
Hemang Vyas

Reputation: 319

Try this...

for i in range(len(l)):
    for j in range(len(l[i])):
        if j < len(l[i]) - 1:
            s = s + str(l[i][j]) +", "
        else:
            s = s + str(l[i][j]) +"\n"
        file.write(s)

Upvotes: 0

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

Try this:

def write(filename, l):
    with open(filename,"w") as file:
         for i,j in l:
             file.write('{}, {}\n'.format(i, j))

If you are using Python3.6 or higher, you can change write line to:

file.write(f'{i}, {j}\n')

Upvotes: 1

576i
576i

Reputation: 8362

Try

def write(filename, l):
    with open(filename, "w") as file:
         for t in l:
             file.write(', '.join([str(s) for s in t]))
             file.write('\n')

Note: it's not necessary to get the length of the list:

for i in range(len(l)):

just get all tuples inside of l

for t in l:

The command below takes all parts of the tuple and converts them to string. The strings are then joined.

', '.join([str(s) for s in t])

Upvotes: 0

Related Questions