简体   繁体   中英

Creating two lists from a text file

I have a text file which consists of inputs:

1 2
3 4
5 6
7 8

I need result or output in the form of:

array_1 = [1, 3, 5, 7]
array_2 = [2, 4, 6, 8]

I have tried the below code:

arr=[]
f = open("file_path","r")
#read line into array

for line in f.read lines():
array_1 = arr.append(line.split()[0])
array_2 = arr.append(line.split()[1])

print(arr)

Why are you appending and assigning the result? (which is None ). As a consequence, all numbers land in arr and array_1 and array_2 are None

A few fixes:

  • use append directly on both lists, forget arr
  • convert to integer when appending

like this:

array_1 = []
array_2 = []
f = open("file_path.txt","r")
#read line into array

for line in f.readlines():
    array_1.append(int(line.split()[0]))
    array_2.append(int(line.split()[1]))

now more pythonic:

  • don't use readlines , read line by line
  • split once and unpack with integer conversion on the fly
  • use with block to open the file, so it's closed when exiting the block

like this:

array_1 = []
array_2 = []
with open("file_path.txt") as f:
    for line in f:
        item1,item2 = map(int,line.split())
        array_1.append(item1)
        array_2.append(item2)

I would go with pandas package for processing such file.

You can then get the two arrays from columns the following way:

import pandas as pd
df = pd.read_csv("D:/tmp/file.csv",delimiter=" ", header=None)
array_1 = df[0].values
array_2 = df[1].values

And output would be:

>>> array_1
array([1, 3, 5, 7], dtype=int64)
>>> array_2
array([2, 4, 6, 8], dtype=int64)

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