在循环中使用 print 和 return 的区别

The difference between use print and return in a loop

好的,我想要的是删除每个较小元组中的第一个元素,并将它们分成两个新元组:(2,3) 和 (5,6)。

a = ((1,2,3),(4,5,6))

def remove_1(tup):
    for r in tup:
        r = r[1:]
        return (r) 

def remove_2(tup):
    for r in tup:
        r = r[1:]
        print(r)

>>>remove_1(x)
(2, 3)
>>> remove_2(x)
(2, 3)
(5, 6)

为什么 remove_1remove_2 给出不同的结果,其中 remove_2 能够处理 A 中的第二个元组而 remove_1 不能?

如何使remove_1到return二元组:

(2,3)
(5,6)

What do I need to change to let the remove_1 return both tuples?

试试这个:

def remove_1(tup):
    result = []
    for r in tup:
        result.append(r[1:])
    return result

如果你想return一个元组,你可以改为return tuple(result)

原因是 return 导致函数立即 return。循环立即停止,函数中不再有代码 运行。

另一方面,print 语句只是将结果打印到屏幕上。允许循环继续处理所有项目。

returnprint 在 运行 交互时似乎是同义词,但它们非常非常不同。您看到的内容 return "prints" 只是因为您 运行 处于交互式环境中。

How to make remove_1 to return two tuple:

一种方法是创建一个变量来保存中间结果,然后在循环结束时 return。请注意,在以下代码中,return 循环之外。

def remove_1(tup):
    result = []
    for r in tup:
        r = r[1:]
        result.append(r)
    return tuple(result)