比较列表并返回新列表

嗨,所以我想对我的函数进行编程,该函数采用一个嵌套列表,一个数字选择一个行,然后一个特定的数字。因此,其假设要做的是接收3个参数height_map(一个嵌套列表),map_row(选择行)和level(一个int)。并返回特定行小于,等于和大于级别的次数。

因此,现在我创建了一个循环,该循环将遍历嵌套列表的特定行,并且我尝试遍历每个数字,查看其是否小于,等于和大于作为第三个参数的级别并返回它

示例是compare_elevations_within_row(THREE_BY_THREE,1,5), THREE_BY_THREE = [[1、2、1],[4、6、5],[7、8、9] 它返回[1,1,1]

def compare_elevations_within_row(elevation_map: List[List[int]],map_row: int,level: int) -> List[int]:
    """Return a new list containing the three counts: the number of
    elevations from row number map_row of elevation map elevation_map
    that are less than,equal to,and greater than elevation level.

    >>> compare_elevations_within_row(THREE_BY_THREE,5)
    [1,1]
    THREE_BY_THREE = [[1,2,1],[4,6,5],[7,8,9]]


    """
    num = elevation_map[map_row]
    count = []
    for index in num:
        if index < level:
            count[0] = count + 1
        elif index== level:
            count[1] = count + 1
        else:
            count[2] = count + 1
    return count
iseehr 回答:比较列表并返回新列表

有一些小问题:

  • count应该用三个零(A)初始化
  • 在给定的count索引处增加值时,应以该索引处的当前值(B)为基础

此外,当您遍历列表时,您遍历列表的,而不是变量名所建议的索引。 (为了清楚起见,我将index更改为value。)

考虑:

def compare_elevations_within_row(elevation_map: List[List[int]],map_row: int,level: int) -> List[int]:
    """Return a new list containing the three counts: the number of
    elevations from row number map_row of elevation map elevation_map
    that are less than,equal to,and greater than elevation level.

    >>> compare_elevations_within_row(THREE_BY_THREE,1,5)
    [1,1]
    THREE_BY_THREE = [[1,2,1],[4,6,5],[7,8,9]]


    """
    count = [0] * 3             # (A)
    for value in elevation_map[map_row]:
        if value < level:
            count[0] += 1       # (B)
        elif value == level:
            count[1] += 1       # (B)
        else:
            count[2] += 1       # (B)
    return count

是您的代码最接近的工作版本。

您还可以探索并考虑使用collections.namedtuple类或dataclass模块作为返回值,而不是“原始”三元素列表。

,

您在这里有2个问题。首先是您的计数列表为空。因此,当您尝试类似count[0] = count + 1之类的操作时,您会遇到IndexError,因为您所指的是不存在的元素(在这种情况下,列表的第一个元素)。您可能想要的不是count = [],而是count = [0,0]

第二个问题是,当您为count[value]递增计数器时,还需要引用右侧的相同列表索引。而不是count[0] = count + 1,您将需要count[0] = count[0] + 1,或者如果您想简洁count[0] += 1

本文链接:https://www.f2er.com/3166039.html

大家都在问