0
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)

How to transform the code above into the while-loop? because there is an if and for-loop again in the code

5
  • Welcome to Stack Overflow. Please take the tour and read about How to Ask. You should post your attempts at this problem so we can help you resolve any errors instead of simply asking for a solution. Commented May 14, 2018 at 4:23
  • Beware: x[0] is not y[0] may not do what you think. is tests for object identity, not value equality. Try this: s='a'; print('ab' is s+'b') Commented May 14, 2018 at 4:36
  • 1
    This may be a time when is is the correct operator (but perhaps not the indexing); note that both x and y iterate over a. But mixing is and == deserves a comment at least, they are not complementary (in which case else would do anyway). Commented May 14, 2018 at 4:50
  • 1
    Could you expand on why you'd want to convert this to while? It's almost always better with for in Python, and I don't see a clear reason in the code. Commented May 14, 2018 at 5:01
  • @YannVernier Indeed, the OP may want to do an identity test here (which is why I phrased my comment that way), but that else makes me suspect that they don't. Commented May 14, 2018 at 5:25

2 Answers 2

2
i = 0

while i < len(a):

  x = a[i]
  i = i + 1
  if x[1] in NERTagger:
    kata = ''
    kt = NERTagger[x[1]]
    j = 0
    while j < len(a):
      y = a[j]
      if x[0] is not y[0]:
          kata += y[0] + ' '
      elif x[0] == y[0]:
          kata +=  kt + ' '
      j = j+1
  hasil.append(kata)
Sign up to request clarification or add additional context in comments.

1 Comment

This answer would be better if you added some explanatory text.
0

There's no problem in using nested for functions.

while is just a general form of for:

for does 3 things:

  • defines a variable.
  • sets a stopping condition.
  • adds 1 to the varaible.

while does 1 of these: sets a stop condition.

2 Comments

Python's for is what's known as foreach in some languages. It processes every item in an iterable and doesn't care if they are numbers or not. That functionality is part of range or itertools.count.
What Yann said. BTW, for is not a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.