我是 python 的新手,总是让我感到困惑的一件事是代码被打成 1 行。以以下为例:
def how_sum(targert_sum, numbers):
table = [None] * (targert_sum + 1)
table[0] = []
for i in range(targert_sum):
if table[i] is not None:
numbers = [num for num in numbers if i + num <= targert_sum]
for num in numbers:
table[i + num] = table[i] + [num]
return table[-1]
这句话numbers = [num for num in numbers if i + num <= targert_sum]
让我感到困惑。我尝试将其分解,使其不在 1 行中,如下所示:
def how_sum(targert_sum, numbers):
table = [None] * (targert_sum + 1)
table[0] = []
for i in range(targert_sum):
if table[i] is not None:
for num in numbers:
if (i + num <= targert_sum):
numbers = [num]
for num in numbers:
table[i + num] = table[i] + [num]
return table[-1]
有人可以解释我哪里出错了,也许可以明确写出扩展的嵌套 for-if 语句吗?
编辑:我认为提供一些问题上下文可能会有所帮助。我正在尝试解决“如何求和”的问题,同时我正在自学一些算法。目标是有一些目标数字(例如 7)和一个列表(例如 [2, 3])并检查列表的元素如何添加到 7(所以 [2, 2, 3])