当我必须选择以特定字母开头的单个单词字符串时,我设法使其起作用。但是,当字符串包含多个单词时,我无法使其正常运行,因此我们不得不比较两个单词的起始字母。
假设,有一个包含字符串的列表,如下所示:
mylist = ["hello world", "hello", "how well", "how world is", "he is great"]
我想选择第一个单词以“ h ”开头和第二个单词以“ w ”开头的字符串。
因此,我期望从上述列表中获得的输出过滤出“ hello world ”和“ 状况” 我想过滤掉不完全包含两个单词的单词。
下面是我到现在为止只检查单词首字母的代码:
for word in mylist:
if word[0]==letter:
print(word)
我尝试了 startswith 的几种变体,但是还没有找到比较字符串中多个单词的方法。
答案 0 :(得分:2)
您可以尝试以下方法:
my_list = ["hello world", "hello", "how well", "how world is", "he is great"]
for phrase in my_list:
words = phrase.split()
try:
if words[0].upper().startswith("H") and words[1].upper().startswith("W") and len(words) == 2:
print(phrase)
except IndexError:
pass
您必须使用try和else,因为如果该短语少于2个项目,则会抛出IndexError。
答案 1 :(得分:2)
稍微递归可以让您根据每个前缀检查每个单词。
mylist = ["hello world", "hello", "how well", "how world is", "he is great"]
prefixes = ['h', 'w']
def filter_prefix(string_list, prefix_list):
def recursive_startswith(words, prefix):
if not prefix:
return True
if words and words[0].startswith(prefix[0]):
words.pop(0)
prefix.pop(0)
return recursive_startswith(words, prefix)
return False
return [x for x in string_list if recursive_startswith(x.split(), list(prefix_list))]
print(filter_prefix(mylist, prefixes))
这也将使您可以匹配所需的任意数量的前缀。
答案 2 :(得分:2)
您可以根据需要编写自定义函数,然后将其传递给python中的内置过滤器函数。
def find_word(string):
mystring = string.split()
return (mystring[0].startswith('h') and mystring[1].startswith('w')
if len(mystring) > 1 else False)
mylist = ["hello world", "hello", "how well", "how world is", "he is great"]
output = list(filter(find_word, mylist)) # filter your list
# ["hello world", "how well", "how world is"]
答案 3 :(得分:1)
尝试:
for word in mylist:
try:
if word.split()[0].startswith('h') and word.split()[1].startswith('w'):
print(word)
except:
pass
split()
按空格分隔单词。这使我们可以访问每个单词,您可以从中进行检查。在此使用,因为应该同时满足两个条件。
同样适用于带有两个单词的字符串:
for word in mylist:
try:
if word.split()[0].startswith('h') and word.split()[1].startswith('w') and len(word.split())==2:
print(word)
except:
pass
这是您的一线客:
[word for word in mylist if len(word.split())==2 and word.split()[0].startswith('h') and word.split()[1].startswith('w')]
没有单线:
for word in mylist:
if len(word.split())==2 and word.split()[0].startswith('h') and word.split()[1].startswith('w') :
print(word)