如何从python3的列表中提取元素?我已经尝试过,但是我做不到的

时间:2019-08-02 06:31:56

标签: python list

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

我尝试在先前的编码问题集中以相同的方式引用行值,并且工作正常。怎么了

以下是出现问题的函数的代码段:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: esse-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
 rules:
 - host: mssmdns.dz
   http:
     paths:
     - path: /esse-1(/|$)(.*)
       backend:
         serviceName: esse-service-1
         servicePort: 8080
     - path: /esse-2(/|$)(.*)
       backend:
         serviceName: esse-service-2
         servicePort: 8080

我希望这部分代码是

@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")

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

percent = row[len(row)-i]

提取表列的值并将其存储为称为行的列表的列表。抱歉,冗长的帖子,请原谅我犯的任何新手错误。谢谢您的帮助。

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

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]

1 个答案:

答案 0 :(得分:0)

KeyError表示row不是list;这是dictlist将引发IndexError。查看示例:

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查询,应该返回listtuple,因此每一行都是一个{ {1}}。

我怀疑在数据库连接设置中是否安装了自定义tuple,使其成为字典。请参阅文档中的example