Openpyxl:如果当前工作表值与值不匹配,则向“删除列表”列表添加列表号

2024-06-16 12:18:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读excel电子表格,试图删除第一列值与“36.0”不匹配的行∞C“或”0.0∞“C”。现在我正在尝试创建一个要删除的行列表,这样在创建了一个包含所有温度值的列表(“temperatureList”)之后,我就可以删除“deleteCellList”列表中的行了。这是我的密码:

temperatureList = []
deleteCellList = []
tempRowNumber = 1

while currentRowValue:
    currentRowValue = sheet[(f"B{tempRowNumber}")].value
    print(type(currentRowValue))
    print("Current Row Value")
    print(currentRowValue)
    if currentRowValue != "0.0 ∞C":
        deleteCellList.append(tempRowNumber)
    elif currentRowValue != "18.0 ∞C":
        deleteCellList.append(tempRowNumber)
    else:
        temperatureList.append(currentRowValue)
    tempRowNumber += 1

print("DCL")
print(deleteCellList)

我发现我遇到的问题是,这个算法将所有单元格相加,其中可能有5-6个值,如下输出所示:

不该是什么样子: DCL公司 [1,2,3,4….]

我想让它看起来像这样:

DCL公司 [45,78,203,408]

我试过打印每个单元格的值,返回类似“36.0”的值∞所以我不认为有任何流氓空间应该把它搞砸。也就是说,到目前为止,我已经尝试了我所知道的一切,是否有任何关于潜在问题/解决方案的直觉


Tags: 密码列表公司温度excelsheet电子表格print
1条回答
网友
1楼 · 发布于 2024-06-16 12:18:00

两种澄清方式:

  1. 在这个问题上使用36.0,但是在代码示例中使用18.0—我假设代码示例中的18.0是正确的
  2. 您引用了“第一列”值,但“B”是第二列,所以我假设您使用的是一个在一列上移位的表

除此之外,问题在于如何应用if逻辑:

if currentRowValue != "0.0 ∞C":          ## If a value does not equal "0.0 ∞C"
    deleteCellList.append(tempRowNumber)
elif currentRowValue != "18.0 ∞C":       ## Otherwise (if the value DOES equal "0.0 ∞C"), if the value does not equal "18.0 ∞C"
    deleteCellList.append(tempRowNumber)
else:                                    ## Otherwise (if the value equals "0.0 ∞C" and also equals "18.0 ∞C")
    temperatureList.append(currentRowValue)

例如“0.0∞C“,”18.0∞C”和“1000.0001∞“C”:

  • “0.0”∞C“=>;失败(=”0.0∞C“)=>;通过(!=“18∞C“)所以添加到deleteCellList
  • “18.0∞C“=>;通过(!=“0∞C“)所以添加到deleteCellList
  • “1000.0001∞C“=>;通过(!=“0∞C“)所以添加到deleteCellList

您要做的是检查值而不是可接受值列表中的值,因此最简单的解决方法是更改逻辑以反映:

if currentRowValue not in ["0.0 ∞C","18.0 ∞C"]:
    deleteCellList.append(tempRowNumber)
else:
    temperatureList.append(currentRowValue)

希望有帮助:)

相关问题 更多 >