Newbie Question : "grep"
Larry Bates
lbates at websafe.com
Mon Mar 12 16:22:42 EDT 2007
moogyd at yahoo.co.uk wrote:
> On 12 Mar, 18:55, attn.steven.... at gmail.com wrote:
>> On Mar 12, 10:01 am, "Erik Johnson" <nob... at invalid.com> wrote:
>>
>>
>>
>>> Sorry, I forgot to paste the modified version of my code in the post:. I
>>> think this is the same behaviour:
>>> for line in lines:
>>> if "placed" in line:
>>> if "i_a/i_b/ROM/" in line:
>>> pos = (line.split()[4]).split("_")[1]
>>> found = False
>>> for (tag, (start, end)) in tags:
>>> if tag in line:
>>> found = True
>>> print " i_a/i_b/ROM/%s [%i:%i] LOC =" %\
>>> (pos, tag, start, end)
>>> break
>>> if not found:
>>> print "Error"
>> Instead of using a sentinal value (i.e., found),
>> one can use the 'else' clause of a 'for' loop...
>>
>> pos = (line.split()[4]).split("_")[1]
>> for (tag, (start,end)) in tags:
>> if tag in line:
>> print " i_a/i_b/ROM/%s [%i:%i] LOC=%s" %\
>> (pos,tag,start,end)
>> break
>> else
>> print "Error"
>>
>> --
>> Hope this helps,
>> Steven
>
> Thanks for the responses.
>
> I had an inkling what the solution may be, but I wondering whether I
> could avoid the nested loops (i.e. loop every line and then loop every
> pattern), maybe using maps or list comprehensions (this is just
> intellectual curiosity as the current solution obviously does the job.
>
> Steven
>
You can certainly get it down pretty small if you turn it into a function
as I did, and use a list comprehension, but I think it is hard to read.
def search(line):
global search_gates
for gate, index in search_gates:
pos = (line.split()[4]).split("_")[1]
if gate in line:
return " i_a/i_b/ROM/%s %s LOC =%s" % (gate, index, pos)
return "Error"
search_gates=[('B6', '[1:0]'), 'B10', '[3:2]'),
'B14', '[5:4]'), 'B17', '[7:6]')]
print '\n'.join([search(line) for line in lines])
-Larry
More information about the Python-list
mailing list