list previous or following list elements

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • antar2

    list previous or following list elements

    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:

    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(li ne)
    a = re.compile("^b" )
    int = 0
    while(int <= list1[-1]):
    int = int + 1
    a_match = a.search(list1[int])
    if(a_match):
    list2.append(li st1[int + 1])
    print list2

    I did not find information about addressing previous or following list
    elements. So some help would be magnificent

    Thanks a lot
  • Zentrader

    #2
    Re: list previous or following list elements

    To be completely correct, you should allow for the possibility that
    the word found is the last word in the list
    for j, word in enumerate(words ):
    if (word.startswit h("b")) and (j+1 < len(words)):
    print words[j+1]
    break

    Comment

    Working...