简体   繁体   中英

Python : Cant append values to a list in a While Loop

I extract some values from Images, now I need to gather all the extracted items from the Image and append them to a List and return them in the end.

What am I doing wrong?

def get_roles_text():
    start = [107, 338, 215, 21]
    while(True):
        im = pyautogui.screenshot(region=(start[0], start[1], start[2], start[3]))
        text = tess.image_to_string(cv2.cvtColor(np.array(im), cv2.COLOR_BGR2GRAY))
        all_roles = list()
        print(text)
        all_roles.append(text)
        print(text)
        start = [start[0], start[1] + start[3], start[2], start[3]]
        if text == '':
            print(all_roles)
            break
            return all_roles

    print(all_roles)

You re-create the list anew on each iteration of the string. Created it before the loop.

Also, your return is never reached, as there is a break in the line before it. See fixes, below, with a few style fixes annotated in comments.

def get_roles_text():
    all_roles = [] # Move it up here. Also, [] is more idiomatic than list()
    start = [107, 338, 215, 21]
    while True: # No need for parens
        im = pyautogui.screenshot(region=(start[0], start[1], start[2], start[3]))
        # Leave out all those print() statements until you need them
        text = tess.image_to_string(cv2.cvtColor(np.array(im), cv2.COLOR_BGR2GRAY))
        if not text: # not text is an idiomatic way to say text == ''
            return all_roles

您的问题是您在循环的每次迭代中都重置列表,您应该在循环外初始化列表。

Init your list outside while loop:

def get_roles_text():
    start = [107, 338, 215, 21]
    all_roles = []
    while(True):
        im = pyautogui.screenshot(region=(start[0], start[1], start[2], start[3]))
        text = tess.image_to_string(cv2.cvtColor(np.array(im), cv2.COLOR_BGR2GRAY))
        print(text)
        all_roles.append(text)
        print(text)
        start = [start[0], start[1] + start[3], start[2], start[3]]
        if text == '':
            print(all_roles)
            break
            return all_roles

    print(all_roles)

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