代码之家  ›  专栏  ›  技术社区  ›  Coolio2654

python:正确使用any()来检查一个数组的一个值是否存在于另一个数组中?

  •  0
  • Coolio2654  · 技术社区  · 6 年前

    在python中,我尝试创建一个if语句,如果一个数组的一个变量存在于另一个列表或数组中的某个位置,则继续执行该语句。这是我的基本代码,它将检查 ids 存在于 follow_num :

    ids = [123,321,111,333]
    follow_num = [111, 222]
    
    if any(ids == follow_num):
        print(ids)
    

    尽管我做了最好的尝试,还有上面的许多版本,但我还是不能让它发挥作用。有人能详细说明我在哪里出了问题吗?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Primusa    6 年前

    必须循环遍历中的每个值 ids 检查是否 any 其中的价值观存在于 follow_num . 使用 任何 了解发电机:

    if any(i in follow_num for i in ids):
        print(ids)
    

    输出:

    [123,321,111,333]
    

    编辑:

    如果你想打印任何匹配的 any() 不起作用,必须使用for循环,因为 任意() 计算整个列表。例子:

    for i in ids:
        if i in follow_num: print(i)
    

    请注意,通过转换 追随者 事先到 set() 通过做 follow_num = set(follow_num) . 这更快是因为 set 有一个 O(1) 在操作中,与计算 in 在里面 O(N) .

        2
  •  1
  •   Darius    6 年前

    或者,您可以比较两组:

    ids = [123, 321, 111, 333]
    follow_num = [111, 222]
    
    matches = list(set(ids) & set(follow_num))
    
    print(matches)
    # [111]
    
    print(bool(matches))
    # True
    
        3
  •  0
  •   jamylak    6 年前
    >>> ids = [123,321,111,333]
    >>> follow_num = [111, 222]
    >>> if set(ids).intersection(follow_num): 
    ...   print(ids)
    ... 
    [123, 321, 111, 333]