#剑指offer#字节流中第一个不重复的字符: filter() 函数过滤掉字节流中重复的字符

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

class Solution:
    def __init__(self):
        self.ls=''
    def FirstAppearingOnce(self):
        s = list(filter(lambda c: self.ls.count(c) == 1, self.ls))
        if s:
            return s[0]
        else:
            return "#"
    def Insert(self, char):
        self.ls += char

filter() 函数
filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
该函数接收两个参数,第一个为函数第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

filter(function, iterable)

注意: Pyhton2.7 返回列表,Python3.x 返回迭代器对象,具体内容可以查看:Python3 filter() 函数

def is_odd(n):
    return n % 2 == 1

newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

参考链接:http://www.runoob.com/python/python-func-filter.html

你可能感兴趣的:(坚持刷题)