第一个例子:元素少的列表匹配元素多的列表,并输入元素少的列表模糊查询匹配的结果。
import re
# 两个示例列表
list1 = ['apple', 'banana', 'orange', 'grape']
list2 = ['apples', 'bananas', 'peach', 'grapes']
# 对每个list1中的元素,在list2中查找是否有模糊匹配项
matches = []
for item1 in list1:
# 使用 re.search 在 list2 中查找是否有匹配项
pattern = re.compile(re.escape(item1), re.IGNORECASE)
match_found = any(pattern.search(item2) for item2 in list2)
if match_found:
matches.append(item1)
print("模糊匹配的元素:", matches)
输出结果:
模糊匹配的元素: ['apple', 'banana', 'grape']
第二个例子:元素多的列表匹配元素少的列表,并输入元素多的列表模糊查询匹配的结果。shu
import re
# 两个示例列表
list1 = ['apple', 'banana', 'orange', 'grape']
list2 = ['apples', 'bananas', 'peach', 'grapes']
# 对每个list2中的元素,在list1中查找是否有模糊匹配项
matches = []
for item2 in list2:
# 使用 re.search 在 list1 中查找是否有匹配项
pattern = re.compile('|'.join(map(re.escape, list1)), re.IGNORECASE)
match_found = pattern.search(item2)
if match_found:
matches.append(item2)
print("list2中含有list1的元素:", matches)
输入结果
list2中含有list1的元素: ['apples', 'bananas', 'grapes']
另外可以用2个for 循环实现相同的功能。
# 两个示例列表
list1 = ['apple', 'banana', 'orange', 'grape']
list2 = ['apples', 'bananas', 'peach', 'grapes']
# 对每个list2中的元素,在list1中查找是否有模糊匹配项
matches = []
for item1 in range(len(list1)):
for item2 in range(len(list2)):
if list2[item2].find(list1[item1]) == -1:
continue
matches.append(list2[item2])
print("list2中含有list1的元素:", matches)
输出结果:
list2中含有list1的元素: ['apples', 'bananas', 'grapes']