Python:为什么要“返回"?不会在简单的for循环中打印出所有列表元素,并且"print"会做的? [英] Python: Why "return" won´t print out all list elements in a simple for loop and "print" will do it?

查看:152
本文介绍了Python:为什么要“返回"?不会在简单的for循环中打印出所有列表元素,并且"print"会做的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我将一个列表附加到另一个列表之后,我试图用Python打印出列表中的所有元素.问题是,当我使用PRINT或RETURN时,它仅打印出每个元素. 如果我使用print,它将在列表末尾的"None"列中打印出整个列表,但是return只会打印出第一项.为什么?

Im trying to print out all elements in a list, in Python, after I´ve appended one list to another. The problem is that it only prints out every element when I use PRINT instead or RETURN. If I use print it prints out the whole list in a column with "None" at the end of the list, but return will print out just the first item. Why?

这是代码:

def union(a,b):
    a.append(b)
    for item in a:
        return item


a=[1,2,3,4]
b=[4,5,6]
print union(a,b)

它返回:

1

如果我使用

def union(a,b):
    a.append(b)
    for item in a:
        print item

a=[1,2,3,4]
b=[4,5,6]
print union(a,b)

相反,我得到:

1

2

3

4

[4、5、6]

没有

(甚至没有一行).

请注意,我在此问题上发现了更多结果(

Please note that I´ve found more results with this issue (like this one), but they are not quite the same, and they are quite complicated for me, I´m just beggining to learn to program, thanks!

推荐答案

使用return语句时,函数结束.您只返回第一个值,循环不会继续,也不能以这种方式一个接一个地返回元素.

When you use a return statement, the function ends. You are returning just the first value, the loop does not continue nor can you return elements one after another this way.

print只会将该值写入您的终端,而不会终止该函数.循环继续.

print just writes that value to your terminal and does not end the function. The loop continues.

建立一个列表,然后返回那个:

Build a list, then return that:

def union(a,b):
    a.append(b)
    result = []
    for item in a:
        result.append(a)
    return result

或仅返回串联:

def union(a, b):
    return a + b

这篇关于Python:为什么要“返回"?不会在简单的for循环中打印出所有列表元素,并且"print"会做的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆