简体   繁体   中英

How to separate a tuple inside a list?

Im working an a project using Tkinter right now. Whenever I input 'Japan', it prints out:

[('Japan', '23,473', 0.0, 985.0, '3,392', '19,096')]

I'm not really sure if that's a list or if it's a tuple? I want to seperate all of that data thats seperated by the commas into different variables. Heres what I have so far. If you see any other holes in my code help would greatly be appreciated. Thanks!

def subby():
        answer=country_name.get()
        l_answer = answer.capitalize()
        sql_command = "SELECT * FROM covid WHERE `name` = ?;"
        values = (l_answer,)
        cursor.execute(sql_command,values)
        data = cursor.fetchall()
        print (data)
        users0.set(data[0])
        users1.set(data[1])
        users2.set(data[2])
        users3.set(data[3])
        users4.set(data[4])
        users5.set(data[5])

Its a list of tuples. As per Mysql Python Connector Docs ,

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

If you're querying with the fixed columns, use namedtuple which will help for better code readability and use.

In [1]: from collections import namedtuple                                                                                                                                   

In [2]: result_set = namedtuple("ResultSet", ["column1", "column2", "column3"])                                                                                              

In [3]: result_set('Japan', '23,473', 0.0)                                                                                                                                  
Out[3]: ResultSet(column1='Japan', column2='23,473', column3=0.0)

In [4]: rs = result_set('Japan', '23,473', 0.0)                                                                                                                             

In [5]: rs.column1                                                                                                                                                          
Out[5]: 'Japan'

What you have right there is a list inside of which there is a tuple, so as to access the first element of the list u can say data[0] and now you have

('Japan', '23,473', 0.0, 985.0, '3,392', '19,096')

this is a tuple.

And you can access items inside tuple by saying data[0][0] which is 'Japan' or data[0][1] which is '23,473' and so on. Hope it cleared you're doubt, lemme know if any errors or doubts:D

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