假设我有一个很大的列表,比如:
list1 = [ "i live in New York's","i play soccer","My friend lives inChicago"]
还有另一个清单:
list2 = ['New York','London','Chicago']
在list1
和list2
中可以有任意数量的元素。你知道吗
我期望的结果是:
i live in New York's -- New York
i play soccer -- No match found
My friend lives inChicago -- Chicago
运行for循环会给我9行匹配和不匹配的数据,但是我需要list1
中的元素来检查所有的list2
,如果找到匹配结果,则给出匹配结果;如果没有匹配结果,则给出匹配结果。如果有多个匹配项,它应该返回最长的匹配字符串。你知道吗
请帮我找到解决办法。你知道吗
检查以下代码。当它遍历list1时,它检查list2中的任何字符串是否存在于list1的字符串中。如果找到多个匹配项,它将打印最长的一个,否则将不打印任何匹配项。你知道吗
输出:
可以将列表理解与
max
函数一起使用:这将输出:
这同样有效。在这里,结果存储在一个列表中,稍后再打印,这样会更整洁一些:
相关问题 更多 >
编程相关推荐