首页 > 解决方案 > 使用 lambda 在列表中查找最小值

问题描述

我有一个将我的数据保存到.txt文件中的代码,然后我使用代码(如下),它在特定列中查找最小值并将其保存到另一个文件中,并在该行中附加了其他信息。输出看起来像这样,当我遇到同样的错误时,我将介绍两种情况。

我的代码:

    rows = []
    with open("S:/Workflow/Testresults/measurements.txt", mode='r') as infile:
        reader = csv.reader(infile, delimiter=" ")
        for row in reader:  # each row is a list
            rows.append(row)
    minimus = min(rows, key=lambda x: float(x[1]))
    dipolemoment = (float(minimus[3]) * ((2*6.532) * pow(10, 22) / (1.06 * pow(10,-10) * 4.5 * cos(radians(int(minimus[0])))))) * pow(10,-24)

错误:

Traceback (most recent call last):
  File "S:/Workflow/NewestDecomp/Decomposition13062019.py", line 198, in <module>
    minimus = min(rows, key=lambda x: float(x[1]))
  File "S:/Workflow/NewestDecomp/Decomposition13062019.py", line 198, in <lambda>
    minimus = min(rows, key=lambda x: float(x[1]))
ValueError: could not convert string to float:

第一的

输出:

30 295.5746708644463
31 287.2952638886134
32 278.71824911973124
33 269.851301784405
34 260.7054651033139
35 251.29568775900006

在这种情况下,脚本可以工作,但如果第一行中的数字超过 100,则会出现错误。

第二

输出:

30 239.69282467921443 0.4676188470692765 
31 233.26309732696078 0.4676188470692765
32 226.55527422794984 0.4676188470692765
33 219.5700525651719 0.4676188470692765
34 212.31067697178025 0.4676188470692765
35 204.78347831156816 0.4676188470692765
36 196.99928467633828 0.4676188470692765

在这里,如果我尝试使用代码,则会出现此错误。第一列中的数字是否高于 100 并不重要。

有什么想法吗?

标签: pythonlambda

解决方案


我认为您可能会看到您阅读的文本文件的格式存在问题。

当我运行代码片段时

rows = []
with open("test.txt", mode='r') as infile:
    reader = csv.reader(infile, delimiter=" ")
    for row in reader:  # each row is a list
        rows.append(row)
    minimus = min(rows, key=lambda x: float(x[1]))

对于您的第一个示例test.txt,但在第一列中修改为具有大于 100 的整数,我不会重现该错误。同样,当我使用第二个示例逐字运行此代码片段时,我不会重现您的错误。

您看到的错误

ValueError: could not convert string to float:

显示无法转换的字符串为空。如果它是一个非空字符串,例如 string notafloat,它将显示为

ValueError: could not convert string to float: notafloat

如果在一行中的第一列和第二列之间有多个空格,则第二列将是空字符串的示例。在这种情况下,您可以将skipinitialspace=True其用作 中的选项csv.reader,这将跳过分隔符后的任何其他空格。


推荐阅读