Python 3在搜索函数中返回false的列表的两个单独成员之间的比较



我一直在努力调试这个函数。该函数的目标是在两个列表之间进行搜索,并打印所有公共列表项。我用print语句对这个嵌套的for循环进行了跟踪和跟踪,但仍无法确定问题所在。循环似乎总是在print语句上返回false,即使比较两个相同的列表项,所以我不认为嵌套的for循环的逻辑是问题所在。

我对Python比较陌生,所以我肯定答案是一些愚蠢的东西。

list_one = [banana, orange, apple]
list_two = [monkey, dog, cat, apple]

def search_lists(list_one, list_two):
match = False

for items in list_one:
for data in list_two:
if (data == items):
print(data)
match = True
print("match found")

return match
search_lists(list_one, list_two)

在列表项周围加上"list_one =["香蕉"、"橙"、"苹果")和list_two =[‘猴子’,‘狗’,‘猫’,‘苹果’]

编辑:如果你想打印列表中匹配的项目列表,那么你也可以使用列表推导:

def search_lists(list_one, list_two):
x = [item for item in list_one for data in list_two if data == item]
return x

list_one = ['banana', 'orange', 'apple']
list_two = ['monkey', 'dog', 'cat', 'apple']
print(search_lists(list_one, list_two))

list_onelist_two初始化错误

  • 如果你希望这些数据是字符串使用
list_one = ["banana", "orange", "apple"]
  • 如果你希望这些数据是变量,在使用之前初始化它们。例如
banana = 0
orange = 1
apple = 2
list_one = [banana, orange, apple]
def intersection_1(lst1, lst2):
lst3 = [value for value in lst1 if value in lst2]
return lst3

def intersection_2(lst1, lst2):
return list(set(lst1) & set(lst2))

def intersection_3(lst1, lst2):
return list(set(lst1).intersection(lst2))

lst1 = ['banana', 'orange', 'apple']
lst2 = ['monkey', 'dog', 'cat', 'apple']
print(intersection_1(lst1, lst2)) # ['apple']
print(intersection_2(lst1, lst2)) # ['apple']
print(intersection_3(lst1, lst2)) # ['apple']

最新更新