【问题标题】:Error assigning None to list item将 None 分配给列表项时出错
【发布时间】:2015-09-23 22:30:26
【问题描述】:

我在我的程序中遇到了一个奇怪的错误,我似乎无法在一个简化的示例中复制它。我正在尝试将 None 的值分配给列表中的项目,但由于某种原因它会引发错误。我不明白这个问题,因为我什至没有使用元组。

#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

【问题讨论】:

    标签: python list tuples mysql-python


    【解决方案1】:

    由于某种原因,MySQLdb 将行作为元组而不是列表返回。尽管使用了 row[:5] 语法,但仍将其复制到 my_list。

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

    由于元组是不可变的,因此必须先将它们转换为列表,然后才能重新分配各个元素。

    my_list = list(row[:5])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多