繁体   English   中英

根据给定的字符串查找匹配元素

[英]Find matching elements based on given string

鉴于我有这个列表,为简单起见。

lst = ['db', 'ca', 'db', 'ae', 'ec', 'sa']    

和字符串'dbaeec'长度总是偶数,主要是 6 或 8。

我们将把它分成 2 个长度的块,然后取第一个'db'找到它,但条件是,它旁边的元素需要是'ae'然后是'ec'

根据上面的列表,我们在索引 0 和 2 处看到了“ db ”。

第一个与下一个元素的 ' ae ' 不匹配,应该被忽略,但后者匹配,即使是第三个 ' ec ',因此输出应该是2

这是我到目前为止尝试过的,

for i, n in enumerate(lst): 
  if n == 'db': 
      if lst[i+1] == 'ae':
          if lst[i+2] == 'ec':
              print(i)
              break

但肯定必须有更好的/pythonic方式吗?

每次获取 3 (len(string)//2)元素将其转换为字符串并与teststring进行比较。

lst = ['db', 'ca', 'db', 'ae', 'ec', 'sa']    
teststring= "dbaeec"
for i in range( len(lst)-len(string)//2 ):
    if "".join( lst[i:i+len(string)//2] ) == teststring:
        print(i, i+len(string)//2)
        break

输出:

2 5

这是一个基于regex的解决方案。 我把它变成了一个可重用的函数。

import re
test_lst = ['db', 'ca', 'db', 'ae', 'ec', 'sa']
test_pat = 'dbaeec'

def find_match_index(needle, haystack):
    m = re.search(needle, ''.join(haystack))
    try:
        return (m.span()[0])/2
    except AttributeError:
        return None

def test(pat, lst):
    match = find_match_index(pat, lst)
    if match is None:
        print("No match was found (function returned None)")
    else:
        print(f"Found match at list index {match}")

print("Test with test data")
test(test_pat, test_lst)
print("Test with non-matchable pattern")
test('x', test_lst)

#output
Test with test data
Found match at list index 2.0
Test with non-matchable pattern
No match was found (function returned None)

这利用了 Python 是一种动态类型语言的事实,在不匹配时返回None 调用者必须测试此返回。 这是因为您可以在索引零处有一个有效匹配,因此零不能作为未找到的标志。

我不喜欢以这种方式操作类型,来自 C 背景。 python中没有法律禁止这样做,但它在以后的代码维护中带来了风险。 如果我有更多的时间并且这是一个更大的项目,我会创建一个“结果”类以保持每个变量的一种类型。

你可以这样做:

这将检查dbaeec的序列dbaeec存在于列表中的任何连续位置。

lst = ['db', 'ca', 'db', 'ae', 'ec', 'sa']    
s = 'dbaeec'

if s in ''.join(lst):
    print ('yes')
else:
    print ('no')

如果你还想在列表中找到索引位置,你可以这样做:

lst = ['db', 'ca', 'db', 'ae', 'ec', 'sa']    
s = 'dbaeec'

i = ''.join(lst).find(s) #do a find after converting the list into a string (using join function) and then searching for dbaeec

if i >= 0:
    print ('Yes, {} is in the list starting index position {}'.format(s,int(i/2)))
else:
    print ('{} is not in the list'.format(s))

输出将是:

Yes, dbaeec is in the list starting index position 2

请注意,上面的代码只会搜索列表中的第一个匹配项。 如果要查找所有出现的情况,则必须稍微修改代码。

尝试这个:

y = "dbaeec"
lst = ['db', 'ca', 'db', 'ae', 'ec', 'sa']

x = ''.join(lst)    
for i in range(0, len(x), 2):
    if x[i:i+len(y)] == y:
        print(i/2)

输出:

2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM