繁体   English   中英

有没有一种方法可以在元组/列表列表中添加索引?

[英]Is there a way to add an index in a list of tuples/list?

假设我有一个元组列表

users = [('Ben', 13),
         ('Ana', 13),
         ('Max', 13)]

其中('Ben',13)将为0,而('Ana',13)将为1 ...

编辑

我有一个来自PySimpleGUI的表,其中显示了一个元组列表。 在表中选择一行将返回行索引。 我想获取绑定到返回的行索引的“用户ID”,以便可以在删除查询中使用它。

这是代码:

import sys
import mysql.connector
import PySimpleGUI as sg

def connect():
    mydb = mysql.connector.connect(
        host='localhost',
        user='root',
        passwd='maning',
        database='usersdb'
    )
    return mydb

mydb = connect()
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM thesisdb.users")
data = mycursor.fetchall() #the list of tuples
headings = ['User ID', 'First Name', 'Last Name', 'Username', 'Password', 'Role']


layout = [[sg.Table(values=data, headings=headings, max_col_width=25,
                        auto_size_columns=True, bind_return_key=True, justification='right', num_rows=20, alternating_row_color='lightgreen', key='users')],
          [sg.Button('Read'), sg.Button('Double')],
          [sg.T('Read = read which rows are selected')],[sg.T('Double = double the amount of data in the table')]]

window = sg.Window('Table', grab_anywhere=False, resizable=True).Layout(layout)

while True:
    event, values = window.Read()
    rowIndex = values['users'] #the index of the selected row
    sg.Popup(index) #displays the index of the selected row

据我所知,该表只能返回所选行的索引。 这就是为什么我问是否可以为每个元组添加索引号的原因,因为我想使用rowIndex获得与所选行具有相同索引号的“用户ID”。

删除查询希望是:

mycursor.execute("DELETE FROM usersdb.users WHERE user_ID = '%s'" % (userID))

@Ev的评论。 Kounis是对的! 元组列表中的每个元组都已经有一个索引。 为了使列表可用作获取所选行的所需元素的参数,剩下要做的唯一一件事就是去掉括号并将其转换为int。

这是代码:

raw = values['users']
x = str(raw).replace('[', '').replace(']', '')
r_index = int(x)
userID = data[r_index][0]

暂无
暂无

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

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