字符串中的Python字符匹配 [英] Python character match in a string

查看:121
本文介绍了字符串中的Python字符匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个函数repfree,该函数将字符串s作为输入,并检查是否有一个字符出现多次。如果没有重复,该函数应返回True,否则返回False。

Write a function repfree(s) that takes as input a string s and checks whether any character appears more than once. The function should return True if there are no repetitions and False otherwise.

我已经尝试过了,但是我不认为这是解决问题的有效方法。

I have tried this but I don't feel this is an efficient way of solving it. Can you suggest an efficient code for this, thanks?

def repfree(s):
    newlist = []
    for i in range(0, len(s)):
        newlist.append(s[i])
    newlist2 = set(newlist)
    if len(newlist) == len(newlist2):
        print("True")
   else:
        print("False")


推荐答案

尝试

chars = 'abcdefghijklmnopqrstuvwxyz'
def repfree(s):
    for char in chars:
        count = s.count(char)
        if count > 1:
            return False
    return True

但是,这还有很长的路要走因为它扫描了列表26次。

But, this is a long way as it scans the list 26 times. A much better and Pythonic way would be

import collections
def repfree(s):
    results = collections.Counter(s)
    for i in results:
        if results[i] > 1:
            return False
    return True

此处, results 是一个字典,其中包含s的所有字符作为键,以及它们各自的频率作为值。此外,检查是否有大于1的值。

Here, results is a dictionary that contains all the characters of s as key, and their respective frequency as value. Further, it is checked if any value is greater than 1, repetition has occurred.

这篇关于字符串中的Python字符匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆