Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove Tuple in List from SQL result

to give some context, I am trying to matched the queried result from SQL with another List. (ie. if List 1 has an item that matches in List 2, it will be stored in Matched_list)

However the output of the queried result (Tally_list) is quite different;
[(‘apple’,), (‘banana’,), (‘pear’,)]

Instead of;
[‘apple’, ‘banana’, ‘pear’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried running the code but it showed 0 result. I suspect it might be because of the tuple that causing it to not match. I have been trying to remove the tuple but to no avai.

Appreciate if anyone can take a look. pardon my rudimentary coding. there is surely better way to optimize this.

import datetime
import mysql.connector

tally_list = ['pear']

cnx = mysql.connector.connect(user='root', password='password',database='db')
cursor = cnx.cursor()

#queries result which is the same time as now
query = ("select fruits from db.table1 where minute(Time) = minute(now())")

cursor.execute(query)

name_list = []

for i in cursor:
    #print(i)
    name_list.append(i)
 
#print(name_list) #[('apple',), ('banana',), ('pear',)]
cursor.close()
cnx.close()

matched_list = []

for item in tally_list:
     for item1 in name_list:
         if item == item1:
             matched_list.append(item)

print(matched_list) #supposed to matched pear

>Solution :

You have to select the first element of the tuple. You can also use a single for-loop together with in.

for item in name_list:
    if item[0] in tally_list:
        matched_list.append(item[0])
print(matched_list) # prints ['pear']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading