将包含特定字母的字符串中的单词添加到列表中

0 投票
3 回答
757 浏览
提问于 2025-04-18 06:31

我有一个字符串,我想找出里面包含“th”的单词,并把它们放到一个列表里。但我不想要包含大写“T”的单词。

最终的列表里不能有重复的单词。

thestring = "The character that can fire the. bullet that sheriff dodged"
a = "th"
b = "T"

def makelists(thestring, a, b)
    """
    >>> makelists(thestring, 'th', 'T')
    ['that', 'the.']
    """

到目前为止,我只得到了这个,但它打印出了重复的单词。

def makelists(thestring, a, b)
    words = thestring.split()
    thelist = [] 
    for word in words:
        if a in word:
            thelist.append(word)           
    for char in thelist:
        if b in char:
            thelist.remove(char)
    print thelist

我得到的输出是 ['that', 'the.', 'that']。

我该如何修改我的代码,才能得到输出 ['that', 'the.'] 呢?

3 个回答

0

试试使用 re 模块和列表推导式,像这样:

import re
thestring = "The character that can fire the. bullet that sheriff dodged"    
a = "th"
b = "T"

print list(set([word  for word in re.split(" +", thestring) if a in word and b not in word ]))
0

使用集合(set)可以让你的代码更简洁,而且可以用更优雅的if语句来处理条件判断:

def makelists(thestring, a, b):
    words = thestring.split()
    thelist = set([]) 
    for word in words:
        if a in word and b not in word:
            thelist.add(word)          
    print thelist
2

虽然你的代码很长,而且需要优化,但你可以在把东西加到列表之前先检查一下:

def makelists(thestring, a, b)
    words = thestring.split()
    thelist = [] 
    for word in words:
        if a in word and word not in thelist:
            thelist.append(word)           
    for char in thelist:
        if b in char:
            thelist.remove(char)
    print thelist

或者,另一种解决办法是这样做:

thelist = list(set(thelist))

撰写回答