2016-10-18 4 views
-3

마지막으로 두 번째 단어를 셀 수있는 파이썬 스크립트를 작성해야합니다. 내 코드입니다 : 내가 가진파이썬에서 마지막 두 번째 단어를 자름

with open('/tmp/values.txt') as f: 
    for sentence in f: 
     list_sentecne = [sen for sen in sentence.rstrip().split(' ')] 

print (list_sentecne) 
op = list_sentecne[-2:-2] 
print (op) 

출력은 다음과 같습니다 : - [

with 

내 생각은 슬라이스를 사용하는 것입니다, 그래서 내가 사용하는 내가 얻을 필요가

['some', 'line', 'with', 'text'] 
[] 

출력은 -2 : -2] 그 목록에서 마지막으로 두 번째 단어를 인쇄 할 수 있지만 스크립트를 실행할 때 출력에서 ​​'빈 목록'점점.

+0

사용'list_sentecne [-2]'. – Evert

+2

This :'sentence in f : list_sentecne = senten.rstrip(). split ('')]'에있는 sen에 대한 센트는별로 의미가 없습니다. 루프를 통해 매 단계마다'list_sentecne'을 덮어 씁니다. – Evert

+0

becoz 파일의 데이터에서 목록을 만들고 싶습니다. –

답변

1

는 요 목록에서 두번째 마지막 요소에서 인쇄해야 -

>>> list_sentecne = ['some', 'line', 'with', 'text'] 
>>> op = list_sentecne[-2:] 
>>> print (op) 
['with', 'text'] 

경우에만 2 마지막 요소

>>> list_sentecne = ['some', 'line', 'with', 'text'] 
>>> op = list_sentecne[-2] 
>>> print (op) 
'with' 
관련 문제