Simple question about python logic.

Colin J. Williams cjw at sympatico.ca
Fri Oct 12 20:41:47 CEST 2007


Tim Chase wrote:
>> I have a file containing following data. But the dimension can be
>> different.
>>
>> A B C D E F G
>> 3 4 1 5 6 2 4
>> 7 2 4 1 6 9 3
>> 3 4 1 5 6 2 4
>> 7 2 4 1 6 9 3
>> .
>> .
>> .
>> .
>>
>> What is the best approach to make a column vector with the name such
>> as A B, etc?
> 
> 
> There are a couple different ways to go about it depending on
> 
> 1) whether just one or whether both dimensions can be different
> 2) whether you want to extract each column vector
> 
> Both of the following should allow for an arbitrary number of
> columns:
> 
> To map everything, you can do something like
> 
> #######################################
> infile = file("in.txt")
> header_row = infile.next().rstrip('\n').split()
> values = [[] for header in header_row]
> for line in infile:
>     line = line.rstrip('\n').split()
>     for dest, value in zip(values, line):
>         dest.append(value)
> infile.close()
> results = dict(zip(header_row, values))
> #######################################
> 
> 
> which you can then use with
> 
> results['A']
> 
> However, if you just want a particular column from the file and
> don't care about the rest, you can do something like
> 
> #######################################
> from itertools import islice
> 
> column_c = [
>  line.rstrip('\n').split()[2]
>  for line in islice(file('in'), 1, None)
>  ]
> #######################################
> 
> where "2" is the zero-based column offset you want (in this case,
> column C = 2)
> 
> -tkc
> 
> 
> 
Numpy appears to have this capability.

Colin W.




More information about the Python-list mailing list