在列表中查找子字符串

时间:2018-02-19 21:53:51

标签: python-2.7 arraylist

我正在尝试从其他列表中排除字符串列表。如果可能的话,我不想使用外部模块。

things = [
"Hotdog1",
"Doc2",
"Hotdog12",
"Doc3",
"Spoon2"
]

exclude = ["Hotdog", "Monkey", "Jam"] # list of things to exclude

for n in things:
  if not n in exclude:
    print n

# >>> "Doc2", "Doc3", "Spoon2" # should be this

只有东西是一个对象,我不能使用startstwith(),因为你可以告诉上面的代码不起作用。什么是最蟒蛇的方式呢?

2 个答案:

答案 0 :(得分:0)

试试这个,它可以更简单的方式完成。我错过了Python lol:P

    class FilterThings(object):
    def __init__(self, things, exclude):
        """

        :param (list) things:
        :param (list)(str) exclude:
        """
        self.things = things
        self.exclude = exclude

    def filter_exclude_things(self):
        filtered = []
        for thing in self.things:
            if not self.check_if_excluded(thing):
                filtered.append(thing)
        return filtered

    def check_if_excluded(self, thing):
        """

        :param (str) thing:
        :return (boolean): True if thing in exclude list else False
        """
        for ex_thing in self.exclude:
            if len(thing) > len(ex_thing):
                result = thing.find(ex_thing)
            else:
                result = ex_thing.find(thing)
            if result > -1:
                break
        else:
            return False
        return True


ft = FilterThings(things1, exclude1)
print ft.filter_exclude_things()
# OP ['Doc2', 'Doc3', 'Spoon2']

答案 1 :(得分:0)

试试这个代码! 我还附上了输出的截图。

things = [
"Hotdog1",
"Doc2",
"Hotdog12",
"Doc3",
"Spoon2"
]

exclude = ["Hotdog", "Monkey", "Jam"] # list of things to exclude

def find(t):
  for i in range(0,len(exclude)):
    if t.find(exclude[i])!=-1:
      return False
    return True


for n in range(0,len(things)):
  if find(things[n]):
    print(things[n])

enter image description here