与第二个字符串列表相比,如何找到一个列表中存在的匹配字符串?

时间:2019-02-14 06:03:43

标签: python

说我有一个很大的清单,例如:

list1 =  [ "i live in New York's","i play soccer","My friend lives inChicago"]

还有另一个列表:

list2 = ['New York','London','Chicago']

list1list2中可以有任意数量的元素。

我想要的结果是:

i live in New York's -- New York
i play soccer -- No match found
My friend lives inChicago -- Chicago

运行for循环为我提供了9行具有匹配和不匹配的行,但是我需要list1中的元素来对所有list2进行检查,并给出匹配结果(如果找到),并且在没有找到时找到匹配项。并且,如果有多个匹配项,则应返回最长的匹配字符串。

请帮助我找到解决方案。

5 个答案:

答案 0 :(得分:1)

检查以下代码。在遍历list1时,它将检查list2的字符串中是否存在list2中的任何字符串。如果找到多个匹配项,它将打印最长的匹配项,并打印无。

list1 =  [ 'i live in New York','i play soccer','My friend lives inChicago']
list2 = ['New York','London','Chicago']

for x in list1:
    print(x)
    match = ''
    for y in list2:
         if y in x:
             if len(y) > len(match):
                 match = y

    if len(match) == 0:
        print(" Matched String: None")
    else:
        print(" Matched String: %s" %(match))

输出:

i live in New York
 Matched String: New York
i play soccer
 Matched String: None
My friend lives inChicago
 Matched String: Chicago

答案 1 :(得分:1)

您可以将列表理解与max函数一起使用:

for i in list1:
    print(' -- '.join((i, max([k for k in list2 if k in i] or ['No match found'], key=len))))

这将输出:

i live in New York's -- New York
i play soccer -- No match found
My friend lives in Chicago -- Chicago

答案 2 :(得分:0)

列表理解对此很有帮助:

matches = []
for item in list2:
  res = [k for k in list1 if item in k]
  matches.append(res)

for match in matches:
  if(len(match) == 0:
    print "No Match"
  else:
    max(match, key=len)

如果使用过滤器或其他功能库,则奖励积分

答案 3 :(得分:0)

这也可以。这里的结果存储在列表中,并在以后打印,这样会更加整洁:

list_1 = ['I live in New York', 'I play soccer', 'My friend lives in Chicago']
list_2 = ['New York', 'London', 'Chicago']

results = []

for str_1 in list_1:
    matches = []

    for str_2 in list_2:
        if str_1.find(str_2) != -1:
            matches.append(str_2)

    if len(matches) != 0:
        results.append(max(matches, key=lambda s: len(s)))
    else:
        results.append('No match found')

print(results)

答案 4 :(得分:0)

list1 =  [ "i live in New York's","i play soccer",'My friend lives inChicago']
list2 = ['New York','London','Chicago']
match_dict = {}
for item1 in list1: 
    s_found = False
    for item2 in list2:
        if item2 in item1:
            s_found = True
            print(item1, '--', item2)
            break
    if not s_found:
        print(item1, '--', 'No Matching Found')