[Tutor] implementing a table data structure in python?

Juan Shen orion_val at 163.com
Tue Dec 21 16:49:32 CET 2004


Maarten,
    First of all, welcome to tutor at python.org
    I've done a little modification on Kent's code to make it more 
sensible.  Please try it.

    Assuming the data file is 'mydata'
$cat mydata
1       1       2       3       23      0.1
13      2       3       4       24      0.15
24      1       1       2       12      0.2
45      2       3       5       1       0.12
116     6       2       7       27      0.18
211     9       4       6       28      0.45

    My python code:
#!/usr/bin/python
#Filename: selectcolumn.py
import sys
datafile='mydata' #Your datafile
columns=[1,2,3,5] #Columns which you'd like to print
try:
    f=open(datafile)
except IOError:
    print "Can't open data file."
    sys.exit()
for line in list(f):
    data=line.split()
    try:
        data=[data[i] for i in columns]
    except IndexError:
        print 'Column index out of range.'
        f.close()
        sys.exit()
    print '\t'.join(data)
f.close()
  
Maarten wrote:

> Hello tutors,
>
> As i'm new to this mailing list so i shall introduce myself. My name 
> is Maarten and except for some shell scripting I have little practical 
> experience in programming (I'm a Linux/Solaris sys-admin). I've doing 
> (mostly) reading about Python. But now trying, despite of my lack of 
> talent for programming, to do write some stuff in Python (i don't call 
> them programs yet;).
>
> So maybe a bit bold for a newbie to start posting a correction but i 
> wanted the code to work:
>
> Kent Johnson wrote:
> <snip>
>
>> columns = [1,3,4]  # Column numbers to show, 0-based
>>
>> f = open('mydata.txt')
>> for line in f:
>>     data = line.split()  # Assuming your data is tab- or space-delimited
>>     data = [ item for i, item in data if i in columns ]  # Filter out 
>> unwanted columns
>>     print data  # Output one row of text - put your formatting here
>>
>> There are probably more efficient ways to extract the data but this 
>> should get you started.
>
>
> guess Kent forgot one line after:
>
>     data = line.split()
>
> adding next line after it:
>
>     data = enumerate(data)
>
> makes it work for me.
>
> Assuming:
> $ cat mydata.txt
> 1   1   2   3   23  0.1
> 13  2   3   4   24  0.15
> 24  1   1   2   12  0.2
> 45  2   3   5   1   0.12
> 116 6   2   7   27  0.18
> 211 9   4   6   28  0.45
>
> Please correct my correction if i'm wrong.
>
> Still got a question. This notation/syntax of the list:
>
> [ item for i, item in data if i in columns ]
>
> is quite new for me. Can someone point me to more examples of this use 
> Or give me the name of it (it must have a name) so i can google it?
>
> thx
> Maarten
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>




More information about the Tutor mailing list