如何将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
iandjas index counters to manually traverse the lista, which mimics how theforloop 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
awere 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 usewhile i < outer_length), but since your original code doesn't altera, this isn't necessary here.
内容的提问来源于stack exchange,提问作者ian lord perdana
相关产品推荐
相关产品推荐

