不久前我遇到了这个问题.找到了此练习的解决方案.我理解逻辑,但我没有得到切片部分.有些东西没有点击.
import itertools as it
def sum_pair(num_list, sum_num):
for num2, num1 in tuple(it.combinations(num_list[::-1], 2))[::-1]:
if num1 + num2 == sum_num:
return num1, num2
num_list = [1, 3, 8, 2, 3, 5, 5, 4, 6, 2, 5, 5, 7, 3, 6, 4, 5, 5]
sum_num = 10
print(f"Sum of pair equals to {sum_num} =", sum_pair(num_list, sum_num))
# Print Output:
# Sum of pair equals to 10 = (8, 2)
现在,为了得到最后一对,我们这样做:
def sum_pair(num_list, sum_num):
for num2, num1 in tuple(it.combinations(num_list[::1], 2))[::-1]:
if num1 + num2 == sum_num:
return num1, num2
# Print Output:
# Sum of pair equals to 10 = (5, 5)
在没有切片的情况下,我们得到以下结果:
def sum_pair(num_list, sum_num):
for num2, num1 in tuple(it.combinations(num_list, 2)):
if num1 + num2 == sum_num:
return num1, num2
# Print Output:
# Sum of pair equals to 10 = (7, 3)
为什么?有人能解释这种行为吗?
我知道[:-1]
是列表中的所有项目,颠倒过来.然而,我不能完全理解这里发生了什么.