0

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']

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
panzer
  • 11
  • 3

1 Answers1

0

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']
Peter234
  • 1,052
  • 7
  • 24