【问题标题】:make the condition in Python在 Python 中创建条件
【发布时间】:2021-04-22 15:16:42
【问题描述】:

有人可以帮忙解决这个问题吗? 我在 Python 上遇到了一个错误,如下面的 ss。

enter image description here

这是我的代码:

longitude_list = []
for i in range(2, maxRow+1):        
    country = sheet.cell(i,7).value
    if country == "United States":
        longitude = sheet.cell(i,6).value
        longitude_list.append(longitude)
        median = np.median(longitude_list)

for i in range(2, maxRow+1):
    country = sheet.cell(i,7).value
    if country == "United States":
        if median.any() > longitude_list:
            if pdsCnt[2] < allocation:
                sheet.cell(i,25).value = pds[2]
                pdsCnt[2]+=1
            else:
                pdsCnt[3] < allocation
                sheet.cell(i,25).value = pds[3]
                pdsCnt[3]+=1    
print(median)

我只是想用这个 'if median.any() > longitude_list:' 创建条件,但是它返回错误。

【问题讨论】:

  • 你想用这个 if 语句实现什么?您正在使用 longitude_list 的中位数并检查它是否小于 longitude_list?您的预期行为是什么?
  • 这是一个 LibreOffice Calc 宏吗?如果是这样,一个示例电子表格将有助于使其正常工作。
  • Other 可以给出更有用的答案,如果你澄清你想在代码后面做什么,特别是条件语句。
  • Please don't post error messages as screenshots。相反,请编辑您的答案以将错误消息包含为引用文本。

标签: python error-handling valueerror


【解决方案1】:

median 的类型是“numpy.float64”,median.any() 是“布尔”,longitude_list 是“列表”。 'bool' 和 'list' 之间的比较没有意义。

由于你没有提到你想要的逻辑,所以我只能猜测:

  1. 您使用了第二个 for 循环,因此您需要单独的 'longitude' 而不是 'longitude_list'。
  2. 你使用了any,所以你想要一个“中值列表”

如果上述情况属实,您需要定义一个“中位数列表”(我们称之为“median_list”),并将每个中位数附加到其中。

那么语句可以是if any(median &gt; longitude for median in median_list):

顺便说一句,您的声明 pdsCnt[3] &lt; allocation 不会更改结果或数据,因此删除它听起来不错。


根据您的评论,以下代码可能有效。由于我不知道allocation 的逻辑,所以我将其从条件中删除。如果重要,您可以将其添加回来或调整。

longitude_list = []
for i in range(2, maxRow+1):        
    country = sheet.cell(i,7).value
    if country == "United States":
        longitude = sheet.cell(i,6).value
        longitude_list.append(longitude)

median = np.median(longitude_list)

for i in range(2, maxRow+1):
    country = sheet.cell(i,7).value
    if country == "United States":
        longitude = sheet.cell(i,6).value
        if longitude > median:
            sheet.cell(i,25).value = pds[2]
            pdsCnt[2]+=1
        else:
            sheet.cell(i,25).value = pds[3]
            pdsCnt[3]+=1    

【讨论】:

  • 嗨杨刘,谢谢你的支持:)顺便说一句,一旦我找到中位数,我实际上想将经度分配给'pdsCnt[2]'和pdsCnt[3]。例如,如果中位数在经度上为 90.xxx,则上述 90 将分配给 pdsCnt[2],而另一个分配给 pdsCnt[3]。所以如果我想这样做,我应该如何编写代码?
  • 不客气,李。我猜你的意思是计算'pdsCnt [2]'的经度。答案中添加的代码。您可能仍需要调整代码,因为逻辑并不完全清楚。顺便说一句,如果遇到问题,建议添加一些打印语句进行调试。
【解决方案2】:

问题是中间值不是一个列表,所以它没有任何称为any()的方法。如果中位数大于列表的任何值,我猜你希望条件返回 true,所以它应该是

if median > any(longitude_list):

【讨论】:

    猜你喜欢
    • 2020-05-25
    • 2010-12-07
    • 2016-12-10
    • 2011-12-13
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    相关资源
    最近更新 更多