简体   繁体   中英

Append every other line from a text file? (Python)

What I'm trying to do is append every other line in my text file into a list, and then the other lines into a serperate list? Eg

Text File 'example'

Item 1
Item 2
Item 3
Item 4
Item 5

So I want 'Item 1', 'Item 3' and 'Item 5' in a list called exampleOne and the other items in a list called exampleTwo?

I've tried for ages to try and work this out by myself by slicing and then appending in different ways, but I just can't seem to get it, if anyone could help it would be greatly appreciated!

from itertools import izip_longest as zip2
with open("some_file.txt") as f:
    linesA,linesB = zip2(*zip(f,f))

is one way you could do something like this

this basically is just abusing the fact that filehandles are iterators

What about

with open('example') as f:
    lists = [[], []]
    i = 0
    for line in f:
        lists[i].append(line.strip())
        i ^= 1

print(lists[0])  # ['Item 1', 'Item 3', 'Item 5']
print(lists[1])  # ['Item 2', 'Item 4']

Or simpler, with enumerate:

with open('example') as f:
    lists = [[], []]
    for i,line in enumerate(f):
        lists[i%2].append(line.strip())

print(lists[0])  # ['Item 1', 'Item 3', 'Item 5']
print(lists[1])  # ['Item 2', 'Item 4']

EDIT

print(lists[0][0])  # 'Item 1' 
print(lists[0][1])  # 'Item 3'
print(lists[0][2])  # 'Item 5'
print(lists[1][0])  # 'Item 2'
print(lists[1][1])  # 'Item 4'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM