简体   繁体   中英

How to iterate through list

I have a list that contains some 20 number of strings , and another list that contains 5 number of strings , I want to check if the list of 5 strings can be found in the set of 20 strings list below is my code

correct_response = []


incorrect_response = []
elements_text = elements1_file.readline().strip()
for ele in elements_text:
    while elements_text:
          if ele == quiz_test:
             correct_response.append(ele)
          elif ele != quiz_test:
               incorrect_response.append(ele)
          else:
              pass
   elements_text = elements1_file.readline().strip()
   print(correct_response,incorrect_response)

Now, the correct response and incorrect cannot be printed, what did I do wrong.

is this what you are looking for? I am assuming that quiz_test is the collection of 5 strings also it appears you should use elements1_file.readlines() instead of elements1_file.readline() and use .strip() on the strings iterated over. I believe your code was iterating over each letter of the first line of the file, instead of each line consecutively.

correct_response = []
incorrect_response = []
elements_text = elements1_file.readline()
for ele in elements_text:
    if ele.strip() in quiz_test:
        correct_response.append(ele)
    else:
        incorrect_response.append(ele)
print(correct_response,incorrect_response)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM