Question

I have two lists results, xvariables and I want to write them out, side by side, on a file results.txt. According to this question, the best way to achieve a side by side lists writing is this:

f = open("results.txt", "w")

    for idx, vals in zip(results, xvariables):
        print idx
        print ('---'.join(vals))

However, i am getting this error:

print ('---'.join(vals))
TypeError

Additionally i need to pair each item of the first list (results) with three items of the second one (xvariables). The abovementioned lists are like that:

results -----> [20.354999999999997, 20.354999999999997]

xvariables --> [2, 3, 4, 2, 3, 4]

So i need 2,3,4 to be written side by side with 20.354999999999997 and so on.

How am I supposed to achieve this?

Was it helpful?

Solution

I'd do it this way:

with open("results.txt", "w") as out:
    xiter = iter(xvariables)
    for idx in results:
        print(idx, next(xiter), next(xiter), next(xiter), file=out)

The idea is to print the three next available values, and using iter/next is a pretty plain way to do that while you iterate in the usual way over results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top