python中的True时,重叠列表函数返回False [英] Overlapping lists function returns False when True in python

查看:84
本文介绍了python中的True时,重叠列表函数返回False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名编程半新手,正在通过Torbjoern Lager的46个简单Python练习进行工作.这是数字10:定义一个函数overlay(),该函数接受两个列表,如果它们至少有一个共同的成员,则返回True,否则返回False.您可以使用is_member()函数或in运算符,但是为了进行练习,还应该使用两个嵌套的for循环将其编写.

I'm a programming semi-noob and am working through Torbjoern Lager's 46 Simple Python Exercises. This is number 10: Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.

def over(list1,list2):
    for i in list1:
        for j in list2:
            return i==j

我以为我有一个很好的简单解决方案,但是除非重叠元素是第一个元素,否则它无法识别出这些列表是重叠的.

I thought I had a nice, simple solution, but it can't recognize that the lists overlap, unless the overlapping elements are the first ones.

over(["a","b","c","d"],["e","f","a","h"]) 

返回False

over(["a","b","c","d"],["a","f","g","h"])

返回True

由于某种原因,它并没有搜索所有组合.任何帮助将不胜感激.

For some reason, it's not searching through all of the combinations. Any help would be appreciated.

推荐答案

在第一次迭代后返回但要使用

You should be testing with an if as suggested in the other answers as you are returning after the very first iteration but using any would be a nicer approach:

def over(list1,list2):
    return any(i ==j for i in list1 for j in list2)

等同于:

def over(list1,list2):
    for i in list1:
        for j in list2:
            if i == j:
                return True
    return False

对比赛进行短路,如果有任何比赛,则返回True;否则,则返回False.

short circuiting on a match and returning True if there is any match or returning False if there are none.

或者将集合用于较大的输入将是最快的方法:

Or using sets for larger input would be the fastest approach:

def over(list1, list2):
    return not set(list1).isdisjoint(list2)

如果not set(list1).isdisjoint(list2)为True,则至少有一个公共元素.

if not set(list1).isdisjoint(list2) is True we have at least one common element.

这篇关于python中的True时,重叠列表函数返回False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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