首页 > 解决方案 > 如何在迭代列表(2)时打印行和相邻行?

问题描述

我有一个列表,其中每个项目都是一个列表,其中包含一个句子和每个句子的分数。

> my_list=[[0,   'ALL TEXT IS RELEVANT\r \r Good day, everyone, and
> welcome to this Apple Incorporated first quarter fiscal year 2017
> earnings release conference call.'],  [-1, "Today's call is being
> recorded."],  [0,   'At this time for opening remarks and
> introductions, I would like to turn the call over to Nancy Paxton,
> Senior Director of Investor Relations.'],  [-1, "Please go ahead,
> ma'am."],  [-1, 'Thank you.'],  [0, 'Good afternoon and thanks to
> everyone for joining us today.'],  [1,   "Speaking first is Apple CEO
> Tim Cook, and he'll be followed by CFO Luca Maestri."],  [0, 'And
> after that, we will open the call to questions from analysts.'],
> etc...

我只想打印一个有特定分数的句子。同时,我还想打印它之前和之后的句子。

具有以下性质的东西:

for line in my_list:
    if line[0]==1:
         print(the line before, line, the line after) 

输出:“下午好,感谢大家今天加入我们。” 首先发言的是苹果首席执行官蒂姆库克,随后是首席财务官卢卡梅斯特里。在那之后,我们将向分析师提问。

我怎样才能做到这一点?

标签: python

解决方案


这应该有效,在列表项是第一个或最后一个的情况下,它会忽略边缘情况:

for i, element in enumerate(my_list):
    if element[0]==1:
        if i>0:
            print(my_list[i-1][1])
        print(my_list[i][1])
        if i<len(my_list)-1:
            print(my_list[i+1][1])

如果您想在线打印它们,请使用print(..., end='')第一个和第二个打印语句


推荐阅读