You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python 3.6中的嵌套For循环转换为While循环?

Got it, let's walk through converting your nested for-loop code into while loops step by step. First, let's fix up the original code's indentation (since it was a bit messy) to make the logic clear:

for x in a:
    if x[1] in NERTagger:
        kata = ''
        kt = NERTagger[x[1]]
        for y in a:
            if x[0] is not y[0]:
                kata += y[0] + ' '
            elif x[0] == y[0]:
                kata += kt + ' '
        hasil.append(kata)

The core idea here is replacing the automatic iteration of for loops with manual index counters for while loops. Here's the equivalent version using while loops, with explanations of each part:

# Initialize counter for the outer loop (replaces for x in a)
i = 0
while i < len(a):
    x = a[i]  # Get the current element from a, just like the for loop does
    if x[1] in NERTagger:
        kata = ''
        kt = NERTagger[x[1]]
        
        # Initialize counter for the inner loop (replaces for y in a)
        j = 0
        while j < len(a):
            y = a[j]  # Grab the current inner element
            # Keep the exact same conditional logic as the original code
            if x[0] is not y[0]:
                kata += y[0] + ' '
            elif x[0] == y[0]:
                kata += kt + ' '
            
            j += 1  # Move to the next element in the inner loop
        
        hasil.append(kata)
    
    i += 1  # Move to the next element in the outer loop

Key notes:

  • We use i and j as index counters to manually traverse the list a, which mimics how the for loop iterates over each element.
  • The conditional checks and string-building logic are identical to the original code—we're just changing how we loop through the elements.
  • If a were modified during the loop (like adding/removing elements), you'd want to store the initial length in a variable first (e.g., outer_length = len(a) and use while i < outer_length), but since your original code doesn't alter a, this isn't necessary here.

内容的提问来源于stack exchange,提问作者ian lord perdana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:28:56