1

I have imported a document. The items show up in a list. I have also taken input from a user, and it tells me where that input is in the list.

How would I print out that line of the list and the item above and below that line in the list? In my list I have actor, name of movie, year, and role the actor played. The middle line is the year so I have the user search for that and it should print out the title of movie and the role they played.

tom = open("TomHanks.txt", "r")
hanksYear = (input('What year would you like to see Tom Hanks movies?'))
hanksRead = tom.readlines()

with open("TomHanks.txt", "r") as f:
    hanksArray = f.read().splitlines()

for i in [i for i, x in enumerate(hanksArray) if x == hanksYear]:
    print(i)

The print(i) gives me the number in the list that year pops up. If it is there twice it gives me both spots that the year pops up. I would like to print that year then print the spot above and below that item in the list.

4

3 回答 3

1

为了其他人的可读性,单独编写答案中的解决方案。

for i in [i for i, x in enumerate(hanksArray) if x == hanksYear]:
        print(hanksArray[i-1])
        print(hanksArray[i])
        print(hanksArray[i+1])
于 2015-10-23T19:40:35.270 回答
0

为您提供快速解决方案

for i in [i for i, x in enumerate(hanksArray) if x == hanksYear]:
    print("\n".join(hanksArray[i-1:i+2]))

无论如何,您的代码还有许多其他问题

于 2015-10-23T19:36:32.047 回答
0

这看起来干净了很多。

for line,val in enumerate(hanksArray):
    if val == hanksYear:
        print(hanksArray[line-1])
        print(val)
        print(hanksArray[line+1])
于 2015-10-23T19:39:04.543 回答