python - 如何在迭代列表(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)
输出:“下午好,感谢大家今天加入我们。” 首先发言的是苹果首席执行官蒂姆库克,随后是首席财务官卢卡梅斯特里。在那之后,我们将向分析师提问。
我怎样才能做到这一点?
解决方案
这应该有效,在列表项是第一个或最后一个的情况下,它会忽略边缘情况:
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='')
第一个和第二个打印语句
推荐阅读
- javascript - 未找到隧道 URL,回退到 LAN URL
- java - 在 Java 中从 Excel 与 DB 中读取数据
- mysql - MySQL- 类似 Timeline 的 Twitter 数据库设计
- mysql - 每 5 分钟更新一次值
- sql-server - 如何设计我的数据仓库来处理迟到的数据源?
- flutter - Flutter保留英雄内部CustomScrollView的滚动位置
- angular - 'MatTableDataSource' 类型上不存在属性 'loading$'
- r - 如何从 R extrafontdb 中注销已删除的字体
- c# - Winforms - LinkLabel 显示缩放?
- python - 列表索引必须是整数或切片,而不是 str 错误 Python