如何在列表中的下一个项目上执行语句,而没有列表索引超出范围
给定列表,我该如何浏览它,如果列表中的下一个项目为空,则不执行操作?
现在我有以下代码。但是我会从范围错误中获得列表索引,因为“ [i+1]
>“混乱”的内容。是否有一种方法可以将诸如“ [i+1]
的诸如i == len(forde)
>“一起”之类的东西?在同一“如果在一起[i+1] ==”“”行?谢谢您的帮助
for i, unit in enumerate(together):
if together[i+1] == "":
final.append(unit)
else:
if unit != "minutes":
unit += ", "
else:
unit += " and "
final.append(unit)
Given a list, how do I go through it, and not do an operation if the next item in the list is empty?
Right now I have code below. But I get list index out of range error since the "together[i+1]
" messes stuff up. Is there a way to get something like "together[i+1]
unless i == len(together)
"? in the same "if together[i+1] == """ line? Thank you for any help
for i, unit in enumerate(together):
if together[i+1] == "":
final.append(unit)
else:
if unit != "minutes":
unit += ", "
else:
unit += " and "
final.append(unit)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
反向列表,以便您不要向前看,而是确定给定当前列表的下一个列表。
Reverse the list so that instead of looking ahead you determine what to do to the next one given the current one.