Home > database >  how to create 3 different list from txt file with 3 columns in python?
how to create 3 different list from txt file with 3 columns in python?

Time:10-09

In python IDLE, I want to create 3 lists from 3 columns in the txt file which contains the following data set :

1.23 2.01 3.15

52.02 958.02 52.02

15.23 59.45 65.78

75.01 25.26 55.26

65.10 98.23 58.45

I want the output like this :

a = [1.23, 52.02, 15.23, 75.01, 65.10]

b = [2.01, 958.02, 59.45, 25.26, 98.23]

c = [3.15, 52.02, 65.78, 55.26, 58.45]

Can anyone pls help me by showing me the code in python IDLE??

CodePudding user response:

Assuming the following input:

s = '1.23 2.01 3.15 52.02 958.02 52.02 15.23 59.45 65.78 75.01 25.26 55.26 65.10 98.23 58.45'

You can use itertools.zip_longest in combination with zip and iter:

from itertools import zip_longest
a,b,c = zip(*zip_longest(*[iter(map(float, s.split()))]*3))

If your input is a multiple of 3, you can use only zip:

a,b,c = zip(*zip(*[iter(map(float, s.split()))]*3))

output:

>>> a,b,c
((1.23, 52.02, 15.23, 75.01, 65.1),
 (2.01, 958.02, 59.45, 25.26, 98.23),
 (3.15, 52.02, 65.78, 55.26, 58.45))

NB. there is actually a recipe for this in itertools documentation (search "grouper")

How it works:

It creates something like zip([<iterator>, <iterator>, <iterator>]]), where iterator is a reference to the same iterator. So each time zip collects a value, it actually takes the next one in the iterator. If the iterator was a list the output shape would be 3 times the input, but as the iterator gets consumed, the final number of elements is conserved (modulo the multiplier).

CodePudding user response:

First, you need to open the file:

file = open("file name")

then make lists for each line using and split each one by the white space:

line1 = file[0].split()
line2 = file[1].split()
line3 = file[2].split()
line4 = file[3].split()
line5 = file[4].split()
lines = [line1, line2, line3, line4, line5]

and make your list using the first element in each line:

a = []
for i in lines:
    a.append(i[0])

b = []
for i in lines:
    a.append(i[1])

c = []
for i in lines:
    a.append(i[2])

and done!

  • Related