简体   繁体   English

Python:无法将值附加到While循环中的列表

[英]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.此外,您的return永远不会到达,因为在它之前的线路中有一个break 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:while循环之外初始化您的列表:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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