嗨,我正在尝试对我的函数进行编程,该函数采用一个嵌套列表,一个数字选择哪个行,然后一个特定的数字。因此,其假设要做的是接收3个参数height_map(一个嵌套列表),map_row(选择行)和level(一个int)。并返回特定行小于,等于和大于级别的次数。
到目前为止,我知道如何在嵌套列表中选择特定的行,但是当我尝试使其嵌套时,它将返回3的列表,但似乎没有作用
示例是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, 1, 5)
[1, 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
有一些小问题:
count
应该用三个零(A)初始化count
索引处的值增加时,应基于该索引处的当前值(B)为基础考虑:
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, 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
模块作为返回值,而不是“原始”三元素列表。