【问题标题】:search list of string with wildcard and return matches & indexes python使用通配符搜索字符串列表并返回匹配和索引python
【发布时间】:2014-04-22 20:36:19
【问题描述】:

给定一个列表

list=['beak','back','bear','kill','keel']

例如,我想使用通配符执行搜索以返回与模式 k**l 匹配的所有单词。我可以通过以下方式轻松做到这一点:

regex=re.compile('k..l')
matches=[string for string in list if re.match(regex, string)]

但是,我还想访问匹配位置的索引并拥有类似的东西:

matches=kill, keel
locs=3,4

我想要索引的原因是,一旦找到匹配项,我想访问 df 中的一整行(包含其他变量)。

感谢您的帮助。

【问题讨论】:

  • 如果你对匹配元组和索引没问题,你可以使用[(idx, string) for idx, string in enumerate(list) if re.match(regex, string)]。然后你可以使用zip来分隔数据。

标签: python regex string wildcard


【解决方案1】:

如我评论中所述,您可以结合enumeratezip 来实现您的目标:

import re

lst=['beak','back','bear','kill','keel']
regex=re.compile('k..l')
locs, matches = zip(*[(idx, string) for idx, string in enumerate(lst) if re.match(regex, string)])
print(matches)
print(locs)

【讨论】:

  • 太棒了!我刚刚进行了编辑(仍需要同行评审)并更改了输出的顺序,因为它将索引和字符串存储在错误的输出中。不过效果很好,谢谢!
猜你喜欢
  • 2018-10-15
  • 2013-08-19
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
  • 2023-03-07
  • 2019-09-04
  • 1970-01-01
相关资源
最近更新 更多