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

2024-10-03 04:25:27 发布

您现在位置: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,如果找到匹配结果,则给出匹配结果;如果没有匹配结果,则给出匹配结果。如果有多个匹配项,它应该返回最长的匹配字符串。你知道吗

请帮我找到解决办法。你知道吗


Tags: infriendlive元素列表newplaymy
3条回答

检查以下代码。当它遍历list1时,它检查list2中的任何字符串是否存在于list1的字符串中。如果找到多个匹配项,它将打印最长的一个,否则将不打印任何匹配项。你知道吗

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

可以将列表理解与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

这同样有效。在这里,结果存储在一个列表中,稍后再打印,这样会更整洁一些:

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)

相关问题 更多 >