0

I am writing a file from a list. The list contains wavelengths and counts. It looks as the example below:

list = ['300','5','400','7','500','4']

What I want to do is to write these elements to a file so that the first column will be the wavelenght entries and the second column will be the count entries.

My solution was to do as follows:

file = open("prøve_fil.TXT","w")

index = 0
while index <= len(lines):
    file.write(lines[index]+'\t'+lines[index+1]+'\n')
    index += 1

Now, I'm aware that this method will arrive at the end of the list and then try to find index+1 and return an error because of the list boundaries. The second thing is that every last entry on a line becomes the first entry on the next line so that the file will look as the example below:

'300'    '5'

'5'    '400'

'400'    '7'

'7'    '500'

'500'    '4'

I think maybe slicing of some sort is my solution, but I can't really see the forest for the trees.

3
  • 1
    Increment index with 2, not 1. Commented Jan 12, 2018 at 8:57
  • Incrementing with two doesn't quite help. This puts every other line as either wavelength or counts so it becomes: '300' '400' '5' '7' Commented Jan 12, 2018 at 9:01
  • index += 2 should rly fix it. Commented Jan 12, 2018 at 9:06

2 Answers 2

4

Use zip with slicing:

>>> for x,y in zip(data[::2], data[1::2]):
...     print(f"{x}\t{y}")
...
300 5
400 7
500 4
>>>

Or you can use this cheeky construction*:

>>> for x,y in zip(*[iter(data)]*2):
...     print(f"{x}\t{y}")
...
300 5
400 7
500 4

The above should give you a taste of the plethora of iterating constructs python offers. However, I suggest sticking with basic looping constructs, such as:

>>> for i in range(0, len(data) - 1, 2):
...     print(data[i],data[i+1])
...
300 5
400 7
500 4

Note, learn to prefer for-loops over while loops. They are less error prone once you get the hang of them. You can do a lot with range. However, here is the equivalent while-loop:

i = 0
while i < len(data) - 1:
    print(data[i], data[i+1])
    i += 2

*Note, although I don't usually use stuff this arcane because I value readability and simplicity, but it is sort of a classic Pythonism. It can be generalized thusly:

>>> def iter_by_n(iterable, n):
...     return zip(*[iter(iterable)]*n)
...
>>> list(iter_by_n(range(9), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]

However, it will give you only up until the last whole partion:

>>> list(iter_by_n(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(iter_by_n(range(11), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(iter_by_n(range(12), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]

This is often the behavior you want, but you can also fill in the partions using itertools.zip_longest with whatever default you want:

>>> from itertools import zip_longest
>>> def iter_by_n(iterable, n, fillvalue=None):
...     return zip_longest(*[iter(iterable)]*n, fillvalue=fillvalue)
...
>>> list(iter_by_n(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
>>> list(iter_by_n(range(10), 3, fillvalue='FOO'))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 'FOO', 'FOO')]
>>> list(iter_by_n(range(11), 3, fillvalue='FOO'))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 'FOO')]
>>> list(iter_by_n(range(12), 3, fillvalue='FOO'))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
>>>
Sign up to request clarification or add additional context in comments.

3 Comments

While the solution is the correct Pythonic one, I would say that in this case it will just confuse the OP or make him just cutpaste the code without understanding it. The OP is struggling with basic indexing iterations.
Yes! Thank you so much!
@imanolLuengo I think I've got slicing down. What I was struggling with was implementing it into looping.
1

Try this way, as an update of your code:

lines = ['300','5','400','7','500','4']
index = 0
while index <= (len(lines) -2):
    print(lines[index] + "\t" + lines[index+1] + "\n")
    index += 2

So you get:

300 5

400 7

500 4

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.