清单追加给无作为的结果 [英] list append gives None as result
问题描述
我刚写应该打印出所有的值2字典有一个共同的功能。
因此,如果使用以下行中我的功能:
i just wrote a function that should print out all the values 2 dictionaries have in common. so if use the following line in my function:
print list_intersection([1, 3, 5], [5, 3, 1])
输出应该是:
[1, 3, 5]
我写了下面code来解决这个问题:
I wrote the following code to solve this problem:
def list_intersection(list_1, list_2):
empty_list = []
for number in list_1:
if number in list_2:
return empty_list.append(number)
问题是,我只能得到无作为输出,但如果我使用下面的code:
The problem is that i only get None as output, but if i use the following code:
def list_intersection(list_1, list_2):
empty_list = []
for number in list_1:
if number in list_2:
return number
我得到打印出来逐个是在两个列表中的数字。我不知道为什么我的程序是不是只是把两个列表有共同的数字到我EMPTY_LIST,回到了我EMPTY_LIST
I get the numbers printed out one by one that are in both lists. I have no idea why my program isn't just putting the numbers both lists have in common into my empty_list and return me my empty_list
推荐答案
我想断言可以作出,这是不完全重复。对于之所以 .append()
收益无
请参阅亚历马尔泰利的博学多才的answer 。
I suppose the assertion could be made that this isn't exactly a duplicate. For the reason why .append()
returns None
please see Alex Martelli's erudite answer.
有关您的code,而不是做的:
For your code instead do:
def list_intersection(list_1, list_2):
intersection = []
for number in list_1:
if number in list_2:
intersection.append(number)
return intersection
这避免了以下缺陷:
- 返回
无
而不是列表交集。 - 返回
无
为的每个的元素list_2
。
- Returning
None
instead of the list intersection. - Returning
None
for each element oflist_2
.
这篇关于清单追加给无作为的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!