[英]Create a list which has only one time each element from two other lists in Python
I'm new in Python and I have to solve a quiz.我是 Python 新手,我必须解决一个测验。 Given two lists of fruits I have to input the missing code in order to return a new list with unique elements from the 2 lists.
给定两个水果列表,我必须输入缺少的代码才能返回一个包含两个列表中唯一元素的新列表。 So the unique_fruits must have
所以 unique_fruits 必须有
["apples", "bananas", "pineapples", "cherries", "strawberries", "oranges", "grapes", "watermelon"] [“苹果”、“香蕉”、“菠萝”、“樱桃”、“草莓”、“橙子”、“葡萄”、“西瓜”]
I do not have to care about the order of the list.我不必关心列表的顺序。
So the given problem is the following所以给定的问题如下
def unique_fruits(fruits1, fruits2):
#write your code here
fruits1 = ["apples", "bananas", "pineapples", "pineapples", "cherries", "strawberries"]
fruits2 = ["oranges", "pineapples", "grapes", "oranges", "cherries", "bananas", "watermelon"]
print(unique_fruits)
My try is the following我的尝试如下
def unique_fruits(fruits1, fruits2):
unique_fruits = list(set(fruits1 + fruits2))
fruits1 = ["apples", "bananas", "pineapples", "pineapples", "cherries", "strawberries"]
fruits2 = ["oranges", "pineapples", "grapes", "oranges", "cherries", "bananas", "watermelon"]
print(unique_fruits)
But getting error "function unique_fruits at 0x7fd3067ffe18"但是出现错误“函数unique_fruits at 0x7fd3067ffe18”
I have to write the missing code only were the # is.我必须编写丢失的代码,只有 # 是。
The only way to get the result is when I have the following code获得结果的唯一方法是当我有以下代码时
def unique_fruits(fruits1, fruits2):
unique_fruits = list(set(fruits1 + fruits2))
fruits1 = ["apples", "bananas", "pineapples", "pineapples", "cherries", "strawberries"]
fruits2 = ["oranges", "pineapples", "grapes", "oranges", "cherries", "bananas", "watermelon"]
unique_fruits = set(listfruits1 + fruits2))
print(unique_fruits)
But as already mention have to complete my code where # is但正如已经提到的,必须完成我的代码,其中 # 是
What am I missing?我错过了什么?
Thanks for your time.谢谢你的时间。
There are a few problems with your code.您的代码存在一些问题。 First of all,
function unique_fruits at 0x7fd3067ffe18
isn't an error, it's printing the location in memory of the function because you didn't include () after the function name, or any parameters for the function.首先,
function unique_fruits at 0x7fd3067ffe18
不是错误,它打印了函数在内存中的位置,因为您没有在函数名称或函数的任何参数之后包含 ()。 Second, instead of defining a variable called unique fruits, you should be returning the value instead.其次,您应该返回值而不是定义一个名为 uniquefruit 的变量。 The following works for me, let me know if you have any more questions:
以下对我有用,如果您还有任何问题,请告诉我:
def unique_fruits(fruits1, fruits2):
return list(set(fruits1 + fruits2))
fruits1 = ["apples", "bananas", "pineapples", "pineapples", "cherries", "strawberries"]
fruits2 = ["oranges", "pineapples", "grapes", "oranges", "cherries", "bananas", "watermelon"]
print(unique_fruits(fruits1, fruits2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.