问题描述
在我将一个列表附加到另一个列表之后,我试图在 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
或者只是返回一个连接:
or just return a concatenation:
def union(a, b):
return a + b
这篇关于Python:为什么“回归"?不会在简单的 for 循环和“打印"中打印出所有列表元素.会做的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!