list previous or following list elements

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Jun 27 03:57:56 EDT 2008


antar2 a écrit :
> Hello
> 
> 
> Suppose I have a textfile (text1.txt) with following four words:
> 
> Apple
> balcony
> cartridge
> damned
> paper
> bold
> typewriter
> 
> and I want to have a python script that prints the words following the
> word starting with the letter b (which would be cartridge) or
> differently put, a script that prints the element following a
> specified element:

def next_if(predicate, iterable):
     if not hasattr(iterable, next):
         iterable = iter(iterable)
     for element in iterable:
         if predicate(element):
             yield iterable.next()


f = open('/home/bruno/text1.txt', 'r')
for elt in next_if(lambda x: x.startswith('b'), f):
     print elt.strip()
f.close()


> I am more experienced in Perl, and a beginner in python
> 
> I wrote a script that - of course - does not work, that should print
> the element in a list following the element that starts with a b
> 
> import re
> f = open('text1.txt', 'r')
> list1 = []
> list2 = []
> for line in f:
> 	list1.append(line)
> a = re.compile("^b")
> int = 0
> while(int <= list1[-1]):
> 	int = int + 1
> 	a_match = a.search(list1[int])
> 	if(a_match):
> 		list2.append(list1[int + 1])
> print list2

f = open('text1.txt')
lines = f.readlines()
f.close()
matchings = [
    next for line, next in zip(lines, lines[1:])
    if line.startswith('b')
    ]

print matchings



More information about the Python-list mailing list