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

在Python中搜索同一列表的多个子列表

  •  -2
  • 5813  · 技术社区  · 11 年前

    我需要Python来搜索给定列表的所有子列表,但当我只搜索其中一个子列表中包含的元素时,这是不起作用的。例如,这是我的代码:

    data = [[4,5],[4,7]]
    search = 4
    for sublist in data:
        if search in sublist:
            print("there", sublist)
    
        else:
            print("not there")
            print(data)
    

    如果我的搜索包含在列表的所有子列表中,这就非常有效。然而,如果我的搜索是,例如,5,那么我得到:

    there [4,5] #I only want this part. 
    not there # I don't want the rest. 
    [[4, 5], [4, 7]] 
    

    编辑: 基本上,我需要Python列出搜索包含的所有列表,但如果搜索只包含在一个子列表中,我只需要 print("there", sublist) 。换句话说,我只想让Python识别搜索所在的位置,而不输出不在的位置,所以不 print("not there") print(data) .

    5 回复  |  直到 8 年前
        1
  •  2
  •   Maria    11 年前

    尝试使用布尔标记。例如:

    data = [[4,5],[4,7]]
    search = 5
    found = false
    for sublist in data:
        if search in sublist:
            print("there", sublist)
            found = true
    if found == false:
        print("not there")
        print(data)
    

    这样,打印数据就在for循环之外,并且不会在每次找到不包含搜索的子列表时打印。

        2
  •  1
  •   roippi    11 年前

    你可能想写的内容:

    data = [[4,5],[4,7]]
    search = 4
    found = False
    for sublist in data:
        if search in sublist:
            found = True
            break
    # do something based on found
    

    一种更好的写作方式:

    any(search in sublist for sublist in data)
    
        3
  •  1
  •   tacaswell    11 年前
    data = [[4,5],[4,7]]
    search = 4
    found_flag = False
    for sublist in data:
        if search in sublist:
            print("there", sublist)
            found_flag = True
    
    #     else:
    #        print("not there")
    #        print(data)
    if not found_flag:
        print('not found')
    

    没有理由将 else 子句,如果您不想对不包括搜索值的子列表执行任何操作。

    妙用 其他的 for 块(但这只会找到一个条目)( doc ):

    data = [[4,5],[4,7]]
    search = 4
    for sublist in data:
        if search in sublist:
            print("there", sublist)
            break
    else:
        print 'not there'
    

    将执行 其他的 如果它在没有击球的情况下完成了整个循环 break .

        4
  •  0
  •   DanGar    11 年前

    你可能正在寻找

    for sublist in data:
        if search in sublist:
            print("there", sublist)
            break
        else:
            print("not there")
    
    print(data)
    
        5
  •  0
  •   rajpython    11 年前

    数据=[[4,5],[4,7],[5,6],[4,5]]

    搜索=5

    对于数据中的子列表:

    if search in sublist:
    
        print "there in ",sublist
    
    else:
        print "not there in " , sublist
    

    在[4,5]中

    在[4,7]中没有

    在[5,6]中

    在[4,5]中

    我刚试过你的代码,在搜索5时没有发现任何错误