python for 循环从 C for 循环转换
python for loop converting from C for loop
以下是单向链表的部分C代码:
for(tptr = start; tptr != NULL && tptr->data < newnode->data; prev=tptr, tptr= tptr->next);
如何将 C 中的 for 循环转换为 Python 中的 for 循环?
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)。
以下是单向链表的部分C代码:
for(tptr = start; tptr != NULL && tptr->data < newnode->data; prev=tptr, tptr= tptr->next);
如何将 C 中的 for 循环转换为 Python 中的 for 循环?
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)。