【问题标题】:How to search if a number from a list is present in another list?如何搜索列表中的数字是否存在于另一个列表中?
【发布时间】:2019-07-24 18:33:00
【问题描述】:

我有一个包含一些数字的列表。我必须一一搜索这些数字以检查它们是否存在于第二个列表中。但我必须完全检查第一个列表中的号码,即如果不存在完全匹配,则从号码中删除最后一位数字并再次搜索直到找到匹配项。我必须对列表 1 的每个数字的所有数字继续这样做。

示例:

z = ['48761', '3876', '481']

p = ['3876112','8935']

我选择3876112...在列表z 中搜索它。如果不匹配,我搜索387611,如果不匹配...我搜索38761 等等...在此过程中的任何时候,如果找到匹配项,我必须返回找到的匹配项,然后开始做同样的事情为8935

注意:如果根本不匹配,我需要返回“不匹配”,并且该号码只有一次。

z = ['48761', '3876', '481']

p = ['3876112','8935']

for m in range(0,len(p)):
    x = p[m]
    for i in range(0,len(x)):
        y = x
        for words in z:
            if y == words:
                print("Found")      
            x = x[:-1]

    print("Not found")

结果:

Found
Not found
Not found

另外,当我在打印行之间添加时,我注意到上面的代码在打印 Found 之前会额外运行一次循环。

【问题讨论】:

  • 当你说“return”时,你的意思是真的“print”吗?
  • 我很确定你有一个缩进错误,由于输入的原因,这是偶然的。 x = x[:-1] 行应该与最内层循环内联。意义应该在那个循环之后发生一次。
  • z 和 p 实际上是来自 2 列的值。结果将在新列中找到或未找到。
  • @Tomerikoo 当我尝试将 x = x[:-1] 与内部循环内联时,我没有得到任何输出。
  • 很奇怪。为我工作...另请参阅将 3876112 更改为 387612 时会发生什么

标签: python python-3.x list


【解决方案1】:

由于您使用的是字符串而不是实际数字,您可以使用str.startswith()

z = ['48761', '3876', '481']

p = ['3876112','8935']

res = []
for target in p:
    for num in z:
        if target.startswith(num):
            res.append("Found")
            break   
    else:
        res.append("Not found")

或者简单地说:

res= ["Found" if any(target.startswith(num) for num in z) else "Not Found" for target in p]

现在,假设您的数据框是 df,您可以这样做:

df["res"] = res

【讨论】:

  • 太棒了!这就像一个魅力。 :)。非常感谢。
【解决方案2】:

使用字符串切片。

z = ['48761', '3876', '481']
p = ['3876112','8935']

for p_ in p:
    length = len(p_)
    found = False
    save = None
    for i in range(length):
        if p_[:length-i] in z: 
            found = True
            save = p_[:length-i]
    if found: print('found', save)
    else: print('not found')

结果是:

found 3876
not found

【讨论】:

  • 非常感谢。那行得通。如果我想将结果作为最终结果,我如何将结果保存在数据框列中而不是列 p?
【解决方案3】:

使用str.startswith()any()提前短路:

z = ['48761', '3876', '481']
p = ['3876112','8935']

for num in p:
    if any(num.startswith(n) for n in z):
        print('Found')
    else:
        print('Not Found')

打印:

Found
Not Found

【讨论】:

    【解决方案4】:

    你可以试试这样的:

    p = ['3876112','8935']
    z = ['48761', '3876', '481']
    
    z = set(z)  # Cast to set for efficient membership search
    
    for elem in p:
        found = False
    
        for i in reversed(range(1, len(elem))):
    
            if elem[:i] in z:
                found = True
                print('Found')
                break
    
        if not found:
            print('Not found')
    

    输出是:

    Found
    Not found
    

    因此列表p 的每个输入元素都有一个输出行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 2021-02-11
      相关资源
      最近更新 更多