迭代列表时出现Python unicode问题

时间:2012-05-19 14:14:28

标签: python django

我有一个Excel工作簿,我想滚动第一列的内容,并将每个唯一值写入新工作簿,即没有重复。

此代码在不检查重复项的情况下运行良好:

def get_data_from_sheet(sheet_index, start_row, end_row, count):
for row in range(start_row, end_row):
    cell = sheet.cell(row,0)
    count = count+1 
    if row != start_row:
        sheet1.write(count,0,cell.value)
return count

但是当我尝试添加条件来检查重复项时,没有任何内容写入Excel文件:

from django.utils.encoding import smart_str

def get_data_from_sheet(sheet_index, start_row, end_row, count):
for row in range(start_row, end_row):
    cell = sheet.cell(row,0)
    count = count+1 
    if row != start_row:
        list.append(smart_str(cell.value))
        if smart_str(cell.value) not in list:
            sheet1.write(count,0,cell.value)
return count

令我困惑的是,因为该列表包含值,即:

enter image description here

那么我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:2)

通过调用:

    list.append(smart_str(cell.value))

之前:

    if smart_str(cell.value) not in list:

您确定测试将始终为False,因为您在测试之前将值附加到列表中。这里的逻辑存在问题。

注意:避免使用内置类型调用变量,调用列表对象lst或其他任何有意义但不使用list作为变量的内容。

相关问题