List对象在append()上返回两个单独的列表

2024-04-26 14:00:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为“search\u suggestion”的函数,它接受search参数并传递到MySQL中,然后将结果附加到下面函数中的空列表“suggestion”中

def search_suggestion(self,search,limit=25):
    """This method takes the parameter search return the search suggestion of employees in database"""
    cursor = None
    suggestions = []
    try:
        cursor = kasaa()
        cursor.execute(
            '''
            SELECT ospos_people.first_name,ospos_people.last_name
            FROM ospos_employees
            INNER JOIN ospos_people ON ospos_employees.person_id = ospos_people.person_id
            WHERE ospos_employees.deleted = 0 AND ospos_people.first_name LIKE %s OR ospos_people.last_name LIKE %s 
            OR ospos_people.phone_number LIKE %s OR ospos_people.email LIKE %s
            ORDER BY ospos_people.first_name ASC LIMIT %s

            ''',(search,search,search,search,limit)
        )
        row  = cursor.fetchall()
        for ro in row:
            suggestions.append(ro["first_name"]+ " " + ro["last_name"])
            print(suggestions)
    except Exception as e:
        print(e)
    finally:
        cursor.close()

我所期望的是一个类似于['alkhadil Issa', 'john Magufuli']的列表 相反,我得到了两份名单。 [alkhadil Issa'] ['alkhadil Issa' 'john Magufuli']

我试着在追加ro["first_name"]之前检查if len(suggestions) < 1:,但是没有得到我想要的。最有效的方法是什么?在我的学习之旅中,您能负担得起的任何患者,我都将不胜感激


Tags: ornamesearchropeoplecursorlikefirst
1条回答
网友
1楼 · 发布于 2024-04-26 14:00:56

我通过手动创建类似于cursor.fetchall()根据您返回的内容的输出来复制您的问题。你知道吗

>>> dic1 = {'first_name': 'Abdallah', 'last_name': 'Abdillah'}
>>> dic2 = {'first_name': 'Joseph', 'last_name': 'Magufuli'}
>>> row = [dic1, dic2]
>>> row
[{'first_name': 'Abdallah', 'last_name': 'Abdillah'}, {'first_name': 'Joseph', 'last_name': 'Magufuli'}]

假设cursor.fetchall()返回类似于上面列表的内容,您的代码应该可以正常工作:

>>> suggestions = []
>>> for r in row:
...   suggestions.append(r['first_name'] + " " + r['last_name'])
...   print(suggestions)
...
['Abdallah Abdillah']
['Abdallah Abdillah', 'Joseph Magufuli']

如果不是这样,那么你的问题就是你的cursor.fetchall()结果。你知道吗


编辑:

我刚意识到你的问题是得到两张单子。请注意,您的print语句位于for循环内,因此每次向列表中添加值时,都会打印结果列表。如果只想在最后打印列表,只需在循环结束后添加print语句:

所以,不是:

>>> for dic in row:
...     suggestions.append(dic['first_name'] + " " + dic['last_name'])
...     print(suggestions)
... 
['Abdallah Abdillah']
['Abdallah Abdillah', 'Joseph Magufuli']

print放在循环外部:

>>> for r in row:
...     suggestions.append(r['first_name'] + " " + r['last_name'])
... 
>>> print(suggestions)
['Abdallah Abdillah', 'Joseph Magufuli']

相关问题 更多 >