繁体   English   中英

检查字符串中的字符是否包含在列表的任何单词中

[英]Check if the characters in a string are contained in any of the word of a list

我需要找到一种方法来检查给定字符是否包含在很长列表的任何单词中。

我想你可以通过检查列表中单词的每个索引来做到这一点,有点像这样:

for i in list:
    if i[0] == 'a' or 'b':
       found_words.append(i)
    if i[1] == 'a' or 'b':
       found_words.append(i)

但这不是一种非常时尚且不是非常有效的方法。

谢谢你的帮助

一种更容易理解的方法如下:

character='e'

for i in list:
    if character in i:
       found_words.append(i)

您可以执行以下操作:

check = set('ab').intersection  # the letters to check against
lst = [...]  # the words, do not shadow the built-in 'list'

found_words = [w for w in lst if check(w)]

或更短:

found_words = list(filter(check, lst))

如果要匹配列表中的字符,可以使用正则表达式。

import re

for i in lst:
    re.match(str,i) #returns "true", use in conditionals

将“str”替换为您要检查的字符,例如“[abcde]”,它匹配任何单词中的“a”、“b”、“c”、“d”或“e”,或“[abcde” ][pqrst]" 匹配 "ap"、"at"、"eq" 等的任意组合。使用变量这样做,这样您就可以更轻松地更改它。

暂无
暂无

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

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