3

I want to execute two for loops at the same time in python, in order to read at the same time two lines with the same index in two different files.

This is what i tried:

def load_dataset(train_path: str, label_path: str) -> Tuple[List[str], List[str]]:
   words = []
   labels = []
   with open(train_path, encoding='utf8') as tp, open(label_path, encoding='utf8') as lp:
       for line_tp in tp, line_lp in lp:
           line_tp = line_tp.strip()
           line_lp = line_lp.strip()
           if line_tp and line_lp:
               word = line_tp
               label = line_lp 
               words.append(word)
               labels.append(label)
   return words, labels

But, when i tried to call the function

(train_list, label_list) = load_dataset(train_path, label_path)

I get:

UnboundLocalError: local variable 'line_lp' referenced before assignment

Now, i really think that the problem is that the first for loop executes before the second loop, is there a way to execute them at the same time, with the same index?

3
  • 2
    python uses zip to "iterate on two(or more) things simultaneously". Commented Apr 7, 2019 at 11:27
  • Possible duplicate of How to iterate across lines in two files simultaneously? Commented Apr 7, 2019 at 11:28
  • @ParitoshSingh thanks, i didn't see that answer, i'm going to try that Commented Apr 7, 2019 at 11:32

3 Answers 3

7

If you want to iterate over to iterators in one loop you should use zip()

for line_tp, line_lp in zip(tp, lp):
Sign up to request clarification or add additional context in comments.

Comments

2

You don't have two for loops at all here. As you should be able to tell from the error traceback, the error will be happening in the for statement itself; because this is not at all how you loop through two separate lists.

It's quite hard to tell what you are trying to do, but I suspect you meant this:

for line_tp, line_lp in zip(tp, lp):

Comments

1

You can use zip to get lines from both files:

for line_tp,, line_lp in zip(tp, lp):
    ....

Comments

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.