Python 查找字符流中的第一个非重复字符

Python 查找字符流中的第一个非重复字符

在本文中,我们将查找字符流中的第一个非重复字符。假设以下是我们的输入−

Thisisit

以下是我们的输出,显示第一个不重复的字符 –

H

使用while循环从字符流中找出第一个不重复的字符

我们将通过使用循环将每个字符与其他字符进行比较,找到第一个不重复的字符−

示例

# String
myStr = "thisisit"

# Looping
while myStr != "":
    slen0 = len(myStr)
    ch = myStr[0]
    myStr = myStr.replace(ch, "")
    slen1 = len(myStr)
    if slen1 == slen0-1:
        print ("First non-repeating character = ",ch)
        break;
    else:
        print ("No Unique Character Found!")

输出

No Unique Character Found!
First non-repeating character =  h

使用函数从字符流中找到第一个不重复的字符

我们还可以创建一个自定义函数,并将字符串传递给它以查找第一个不重复的字符 –

示例

# Custom function
def RepeatingFunc(myStr):
    char_order = []
    counts = {}

    for c in myStr:
        if c in counts:
            counts[c] += 1
        else:
            counts[c] = 1
            char_order.append(c)
    for c in char_order:
        if counts[c] == 1:
            return c
    return None

print("First Non-Repeating Character = ",RepeatingFunc('thisisit'))

输出

First Non-Repeating Character =  h

使用Counter()从字符流中找到第一个非重复字符

Counter也可以用来从Collections模块中找到第一个非重复字符。该模块实现了特殊的容器数据类型,提供了Python通用内建容器dict、list、set和tuple的替代品-

示例

from collections import Counter

def repeatFunc(myStr):

    freq = Counter(myStr)

    # Traverse the string
    for i in myStr:
        if(freq[i] == 1):
            print(i)
            break

# Driver code
myStr = "thisisit"

repeatFunc(myStr)

输出

h

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程