如何在列表中的下一个项目上执行语句,而没有列表索引超出范围

发布于 2025-01-23 18:46:02 字数 507 浏览 0 评论 0原文

给定列表,我该如何浏览它,如果列表中的下一个项目为空,则不执行操作?

现在我有以下代码。但是我会从范围错误中获得列表索引,因为“ [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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡看悲欢离合 2025-01-30 18:46:02

反向列表,以便您不要向前看,而是确定给定当前列表的下一个列表。

together.reverse()

skip = False

for unit in together:

    if(not skip):

        # If current entry is blank skip the next one
        if unit == "":
             skip = True

        else:
             # Current entry is not blank and the last entry is not blank
             # IDK if this is what you want to do in the loop or not, copied from your question
             if unit != "minutes":
                 unit += ", "
             else:
                 unit += " and "
             final.append(unit)

    else:
        skip = False

together.reverse()

Reverse the list so that instead of looking ahead you determine what to do to the next one given the current one.

together.reverse()

skip = False

for unit in together:

    if(not skip):

        # If current entry is blank skip the next one
        if unit == "":
             skip = True

        else:
             # Current entry is not blank and the last entry is not blank
             # IDK if this is what you want to do in the loop or not, copied from your question
             if unit != "minutes":
                 unit += ", "
             else:
                 unit += " and "
             final.append(unit)

    else:
        skip = False

together.reverse()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文