text = '''www.something0.com
get the 2 above
www.somethingss1.com
get the 2 above
www.somethingssss2.com
get the 2 above
www.somethingss3.com
get the 2 above
www.somethingss4.com
www.somethingss5.com
get the 2 above'''
from collections import deque
above = deque(maxlen=2)
for x in text.splitlines():
if 'get the 2 above' in x:
print above
elif x:
above.append(x)
print '\n=================\n'
# Senderle's code:
s = text.splitlines()
for i, line in enumerate(s):
if 'get the 2 above' in line:
print s[i-1], s[i-2]
結果
deque(['www.something0.com'], maxlen=2)
deque(['www.something0.com', 'www.somethingss1.com'], maxlen=2)
deque(['www.somethingss1.com', 'www.somethingssss2.com'], maxlen=2)
deque(['www.somethingssss2.com', 'www.somethingss3.com'], maxlen=2)
deque(['www.somethingss4.com', 'www.somethingss5.com'], maxlen=2)
=================
www.something0.com get the 2 above
www.somethingss1.com
www.somethingssss2.com
www.somethingss3.com
www.somethingss5.com
はtext'は意味 'です文字列または開いているファイルオブジェクトにするには? –
これは文字列であることを意味します –
この場合、 'for a text in'ループは文字列の文字をループしますが、おそらく' for a text.splitlines() 'を意図しています。 –