我需要编写一个python脚本来计算倒数第二个字。我的代码是:
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)
我获得的输出是: -
['some', 'line', 'with', 'text']
[]
我需要获得的输出是:
with
我的想法是使用切片,所以我使用[-2:-2]这样它将在列表中打印最后一个字,但是当我运行脚本时,我在输出处得到'空列表'。
答案 0 :(得分:1)
哟需要从列表中的第二个元素打印 -
>>> list_sentecne = ['some', 'line', 'with', 'text']
>>> op = list_sentecne[-2:]
>>> print (op)
['with', 'text']
如果只是第二个最后一个元素
>>> list_sentecne = ['some', 'line', 'with', 'text']
>>> op = list_sentecne[-2]
>>> print (op)
'with'