【问题标题】:python for loop converting from C for looppython for循环从C for循环转换
【发布时间】:2021-10-15 05:47:57
【问题描述】:

以下是单链表的部分C代码:

for(tptr = start; tptr != NULL && tptr->data < newnode->data; prev=tptr, tptr= tptr->next);

如何将 C 中的 for 循环转换为 Python 中的 for 循环?

【问题讨论】:

  • 不要将所有逻辑都放在 for 语句中。它使代码难以理解。
  • 如果您提供完整的、可重现的示例,我们可以帮助您将其转换为 python。事实上,我们必须对您使用的数据结构做出一些假设。

标签: c python-3.x for-loop while-loop


【解决方案1】:

在 C 中

for(tptr = start; tptr != NULL && tptr->data < newnode->data; prev=tptr, tptr= tptr->next);

等价于

tptr = start;
while (tptr != NULL && tptr->data < newnode->data) {
  prev = tptr;
  tptr = tptr->next;
}

C 风格的for 循环更像是while 循环。用 for 构造在 Python 中表达它当然是可能的(例如,编写一个永远运行的 for 循环,如果条件不满足则中断),但这不是最佳实践。

在 Python 中,我建议使用 while 循环来表达您的示例(除非它是一个简单的 for-循环,例如迭代数字 0 到 n)。

【讨论】:

    猜你喜欢
    • 2012-10-13
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多