问题
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])
The output should be:
[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)
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
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
回答1:
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
This avoids the following pitfalls:
- Returning
None
instead of the list intersection. - Returning
None
for each element oflist_2
.
来源:https://stackoverflow.com/questions/26151795/list-append-gives-none-as-result