简体   繁体   中英

Python make a list out of text file with one element on each line

I have a text file with a list of numbers (one on each line), is it possible to make a list out of that text file where there is one number on one line? I need this so that I can go through the list of numbers in pairs where I take the two first numbers first, 3rd and 4th after that and go through the whole file like that, untill there is no numbers left. Currently I get all of the numbers on the same line, but it gets tricky when I would need to use so other than the two first numbers.

list = []
file = open("doc.txt", "r")
for line in file:
list.append(line.strip())

EDIT: I have been trying to approach this with unnecessary complexity. I can just used the index of the list to make it work (I assume)

You can do the following to get the pairs:

with open("doc.txt", "r") as file:
    lst = [line.strip() for line in file]  # do not shadow built-in name `list`
pairs = [lst[i:i+2] for i in range(0, len(lst), 2)]

Another (more elegant) way without an intermediate list (more space efficient) goes straight to the pairs using the involved iterators:

with open("doc.txt", "r") as file:
    nums = map(str.strip, file)
    nums = map(int, nums)  # if needed for calculations
    pairs = [*zip(nums, nums)]

for a, b in pairs:
    print(a + b)
    print(a - b)
    # ...

Have a look here. After you build your list, split it in a new list where each element is a list of two elements, and after that itherate over new list.

list = []
file = open("doc.txt", "r")
for line in file:
    list.append(float(line.strip()))
pairs = [list[2*i:2*i+2] for i in range(0, len(list)/2)]
for x1,x2 in pairs:
    print("Calculate ({}, {})".format(x1, x2))

I've put in the text file the number 1...10 one per line, and the output is

Calculate (1.0, 2.0)
Calculate (3.0, 4.0)
Calculate (5.0, 6.0)
Calculate (7.0, 8.0)
Calculate (9.0, 10.0)

Assumption is that the text file has valid data: numbers and even number of lines.

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