提取网格匹配字符串的Python程序
给定一个包含缺失字符的字符网格,匹配与网格匹配的字符串。
例子:
Input : test_list = [“geeks”, “best”, “peeks”], mesh = “_ee_s”
Output : [‘geeks’, ‘peeks’]
Explanation : Elements according to mesh are geeks and peeks.
Input : test_list = [“geeks”, “best”, “test”], mesh = “_e_t”
Output : [‘best’, ‘test’]
Explanation : Elements according to mesh are best and test.
方法#1:使用loop + all() + len() + zip()
以上的组合可以用来解决这个问题。在此,我们使用 zip() 和 all() 执行匹配网格和每个字符串的任务,用于检查所有字符串,使用 len() 测试匹配网格的字符串长度是否正确。
Python3
# Python3 code to demonstrate working of
# Extract Mesh matching Strings
# Using len() + loop + zip() + all()
# initializing list
test_list = ["geeks", "best", "peeks", "for", "seeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing mesh
mesh = "_ee_s"
res = []
for sub in test_list:
# testing for matching mesh, checking each character and length
if (len(sub) == len(mesh)) and all((ele1 == "_") or (ele1 == ele2)
for ele1, ele2 in zip(mesh, sub)):
res.append(sub)
# printing result
print("The extracted strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Mesh matching Strings
# Using list comprehension
# initializing list
test_list = ["geeks", "best", "peeks", "for", "seeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing mesh
mesh = "_ee_s"
# one liner to solve this problem
res = [sub for sub in test_list if (len(sub) == len(mesh)) and all((ele1 == "_") or (ele1 == ele2)
for ele1, ele2 in zip(mesh, sub))]
# printing result
print("The extracted strings : " + str(res))
输出
The original list : ['geeks', 'best', 'peeks', 'for', 'seeks']
The extracted strings : ['geeks', 'peeks', 'seeks']
方法#2:使用列表理解
这以与上述方法类似的方式解决了该问题,唯一的区别是提供了 1 个 liner 解决方案。
蟒蛇3
# Python3 code to demonstrate working of
# Extract Mesh matching Strings
# Using list comprehension
# initializing list
test_list = ["geeks", "best", "peeks", "for", "seeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing mesh
mesh = "_ee_s"
# one liner to solve this problem
res = [sub for sub in test_list if (len(sub) == len(mesh)) and all((ele1 == "_") or (ele1 == ele2)
for ele1, ele2 in zip(mesh, sub))]
# printing result
print("The extracted strings : " + str(res))
输出
The original list : ['geeks', 'best', 'peeks', 'for', 'seeks']
The extracted strings : ['geeks', 'peeks', 'seeks']