[Tutor] Grep equiv.
Thu, 31 Aug 2000 23:23:56 +0100
Scott already answered about the trouble with "if result!='-1'". let me
try to answer your other questions.
Wes Bateman wrote:
> I tried to use string.splitfields(line) to break it up, but it used a
> whitespace delimeter and divided each line up. If I did this the
> string.find choked on the list variable type. Which raises other
> questions I have about how I can perform a particular function on all of
> the items in a list ( variable, variable, variable, etc.) in one
This is the map function:
>>> def f(x):
... return x**2
[0, 1, 4, 9, 16]
> Further, what would be the preferred way to suck a file in, put each line
> in a variable, and each field in each line inside of that? I understand
> that I can nest lists, so maybe like file is first line of file and
> inside of that there could be several fields? How would I reference them
> and how could I get them into a structure like that?
The way you read it in your script dows just that, but you have to
assign to a variable to keep it:
The hole file was read and you now have a list called lines such that
lines is the fisrt line of the file, line is the second line of
the file, and so on. There are other ways as well. Check the tutorial.
Wich one is best depends on what you want to do and what you want to do
it to. For instance, it's probably not a good idea to read in one deep
gulp a 2 million line file. That's what happens if you use readlines to
> Eventually I want to take say the third field from each line that matches
> my "grep-like" function and add them.
You can add the 3rd fields of each line with
for line in lines: #lines is the list read above
This assumes that the fields are separated with whitespace.
string.split splits line into fields, and field #3 is is the one with
(1st position has index 0, 2nd position has index 1..... n-th position
has index n-1). float converts the string into a number, it possible.
float('3') returns 3.0; float('hello!') returns an error.
Cheers, and good luck!