list append 给出 None 结果 [英] list append gives None as result

查看:33
本文介绍了list append 给出 None 结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚编写了一个函数,该函数应该打印出 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]

我写了以下代码来解决这个问题:

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)

问题是我只得到 None 作为输出,但如果我使用以下代码:

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() 返回 None 的原因,请参阅 Alex Martelli 的博学 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.

对于您的代码,请执行以下操作:

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. 返回 None 而不是列表交集.
  2. list_2每个 元素返回 None.
  1. Returning None instead of the list intersection.
  2. Returning None for each element of list_2.

这篇关于list append 给出 None 结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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