简体   繁体   English

为列表项分配“无”时出错

[英]Error assigning None to list item

I'm getting a strange error in my program which I can't seem to replicate in a simplified example. 我的程序中出现一个奇怪的错误,在简化的示例中似乎无法复制。 I'm trying to assign the value of None to an item in a list, but for some reason it throws an error. 我正在尝试将None的值分配给列表中的项目,但由于某种原因,它将引发错误。 I don't understand the problem, since I'm not even using tuples. 我不明白这个问题,因为我什至没有使用元组。

#Execute SQL query returning five columns.
cursor.execute(query)

#Iterate the rows.
for row in cursor:
    #Get one row, and copy it to a new list variable.
    my_list         = row[:5]

    #If index 3 is zero, convert it to None.
    if (my_list[3] == 0):
        print type(my_list[3])
        ##Prints <type 'int'>

        my_list[3]  = None
        ##TypeError: 'tuple' object does not support item assignment

For some reason, MySQLdb returns rows as tuples instead of lists. 由于某种原因,MySQLdb将行作为元组而不是列表返回。 This is getting copied to my_list, in spite of the row[:5] syntax. 尽管使用row[:5]语法,但仍将其复制到my_list。

print type(my_list)
##Prints <type 'tuple'>

Since tuples are immutable, they must be first converted to lists, after which individual elements can be reassigned. 由于元组是不可变的,因此必须首先将它们转换为列表,然后才能重新分配各个元素。

my_list = list(row[:5])

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

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