使用re检查列表中是否存在元素

时间:2018-05-24 02:36:29

标签: python python-2.7

如何以有效的方式使用re方法检查列表中是否存在元素?

list = ['abc', 'efg','xyz:3+1']
a = "efg"
if a in list:
    print "element exist"
else:
    print "element not exist"


Expected Output:element exist


if a = "123"
Expected output: element not exist
if a = "xyz"
Expected output: element not exist

我必须实现的是a是xyz:number + number,然后打印“element exists”。

if a = "xyz:10 + 5" 
Expected Output:element exist
if a = "xyz:3 + 1" 
Expected Output:element exist
if a = "xyz:10 + " 
Expected Output:element not exist
if a = "xyz:10" 
Expected Output:element not exist

1 个答案:

答案 0 :(得分:0)

使用如下:

import re
alist = ['abc', 'efg', 'xyz:3+1']
patt = re.compile(r'xyz:\s*\d+\s*\+\s*\d+\s*$')

def check_exist(e, alist, patt=patt):
    if e in alist:
        return "element exist"
    if patt.match(e):
        t = [i for i in alist if patt.match(i)]
        return "similar elements found: {}".format(t)
    return "element not exist"

a = "efg"
print(check_exist(a, alist))
a = "xyz:10 + 5"
print(check_exist(a, alist))

输出:

element exist
similar elements found: ['xyz:3+1']