清单追加给无作为的结果 [英] list append gives None as result

查看:157
本文介绍了清单追加给无作为的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚写应该打印出所有的值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

这避免了以下缺陷:


  1. 返回而不是列表交集。

  2. 返回的每个的元素 list_2

  1. Returning None instead of the list intersection.
  2. Returning None for each element of list_2.

这篇关于清单追加给无作为的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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