首页 > 解决方案 > 如何从python3中的列表中提取元素?我试过了,但我所做的没有用

问题描述

我已经(据说成功地)从 SQLite3 数据库中的表中提取了值行,但是在尝试从行中提取值以保存在变量中时出现“KeyError:16”。该行是一个列表,应该包含 19 个元素。为什么我会收到 KeyError:16 ?

我尝试在先前的编码问题集中以相同的方式引用行值,并且效果很好。这里有什么问题?

这是有问题的函数的代码片段:

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method=="POST":
        #cancerlist is the name of the html select menu,
        #and below I'm getting the type of cancer the user 
        #selected, and saving it in a variable called selection.
        #based on the selection, I want to return a different html
        #file for each selection, to display info about medications
        #used for that type of cancer, and their side effects.
        selection = request.form.get("cancerlist")
        if selection == "breast cancer":
            #declaring lists to use later.
            side_effects_list=[]
            percentages_one=[]
            rows = db.execute("SELECT * FROM 'breast cancer'")
            for row in rows:
                i = 3
                while len(row) > 0:
                    #make list of side effects percentages for 
#breast cancer medications, by appending percentages to a list,
                    #starting from the side effects, and not 
#appending the id, medication name, and dosage form, which are
#in the last 3 columns of the table.
                    percent = row[len(row)-i]
                    percentages_one.append(percent)
                    i+=1
                    if len(row) == 0:
                        side_effects_list = ("cardiac side 
effects", "hepatotoxicity", "peripheral neuropathy", 
"thrombocytopenia", "alopecia", "headache", "vomiting", "decreased 
appetite", "leukopenia", "anemia", "fatigue", "infections", 
"abdominal pain", "nausea", "neutropenia", "diarrhea" )
                        fig, ax = plt.subplots()
                        ax.barh(percentages_one, side_effects_list)
        #I want to plot a graph using side effects of medications 
#on the x-axis and percentage of occurence of the
        #side effects on the y-axis, but I haven't figured out how 
#to do that yet, so part of the code won't make sense,
        #but up till i+=1 I thought was implemented correctly, and 
#do not know why I get KeyError: 16.
        return render_template("breastcancer.html")

    else:
        return render_template("index.html")

我希望这部分代码:

percent = row[len(row)-i]

从名为“row”的列表中提取一个元素,并将其保存在名为“percent”的变量中,但是我在终端中收到一个错误,指出“KeyError:16”。这没有意义,因为我的表中有 19 列,并且我实现了以下内容:

rows = db.execute("SELECT * FROM 'breast cancer'")

提取表列的值并将它们存储为称为行的列表列表。对不起,很长的帖子,请原谅我犯的任何初学者的错误。谢谢您的帮助。

更新:我更改了以下内容:

percent = row[len(row)-i]

至:

percent = row.pop[len(row)-i]

我得到了这些回溯:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 
39, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/ubuntu/environment/justforme/application.py", line 45, in 
index
    percent = row.pop[len(row)-i]
TypeError: 'builtin_function_or_method' object is not subscriptable
INFO:werkzeug:192.168.143.110 - - [02/Aug/2019 07:16:00] "POST / 
HTTP/1.0" 500 -

此外,尝试时:

percent = row[len(row)-i]

代替:

percent = row.pop[len(row)-i]

我得到以下回溯:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
    1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", 
line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 
1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/ubuntu/environment/justforme/application.py", line 45, 
in index
    percent = row[len(row)-i]
KeyError: 16
INFO:werkzeug:192.168.180.145 - - [02/Aug/2019 07:37:49] "POST / 
HTTP/1.0" 500 -

标签: pythonlist

解决方案


a不是 a的KeyError手段;这是一个。A会加注。查看示例:rowlistdictlistIndexError

In [1]: a = list(range(4))                                                                               
Out[1]: [0, 1, 2, 3]

In [2]: a[5]                                                                                             
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-2-4a84d856522b> in <module>
----> 1 a[5]

IndexError: list index out of range

In [3]: b = {1: 'a', 2: 'b'}                                                                             
Out[3]: {1: 'a', 2: 'b'}

In [4]: b[16]                                                                                            
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-4-b20f10bd21e5> in <module>
----> 1 b[16]

KeyError: 16

要遍历字典,您可以使用以下items()方法:

In [5]: for key, value in b.items(): 
   ...:     print(f'key={key}, value={value}') 
   ...:                                                                                                  
key=1, value=a
key=2, value=b

编辑:虽然很奇怪。通常在 sqlite3 数据库上执行SELECT查询返回 a listof tuples,因此每一行都是 a tuple

我怀疑在数据库连接设置中,您安装了一个自定义row_factory,使其成为一个字典。请参阅文档中的此示例


推荐阅读