测试字符串是否重复字符

时间:2015-08-19 08:17:02

标签: python python-3.x collections

我试图找出最轻的方法来确定一个字符串是否有任何重复的字符,尽可能以最轻的方式。我试图寻找类似的问题,但无法找到任何问题。它也需要是短路的方式,因为我将检查相当多的字符串(我可以处理将它放入循环等)

例如:

a = "12348546478"
#code to check multiple characters
print(result) 

结果:重复8次,重复4次

代码将检查重复的字符并打印出重复的内容。我不需要知道它重复了多少次,只是重复是否重复。

7 个答案:

答案 0 :(得分:6)

或者你可以做

len(set(x)) == len(x)

如果字符串没有重复字符,则返回布尔值True,否则返回False

set类型不能有任何重复项,因此当字符串变为一个时,它会被分解为字符。长度差异显示有多少重复字符(但不是字符本身)

答案 1 :(得分:3)

您可以使用collections.Counter

if (IsManager)
{
    context.Managers.Add(employeeRow as Manager);
    context.Employees.Add(employeeRow as Employees);  // throw errors
    context.SaveChanges();
}
else
{
  context.Managers.Add(employeeRow as Employee);
  context.SaveChanges();
}

或者您可以使用自定义功能:

>>> from collections import Counter
>>> [i for i,j in Counter(a).items() if j>1]
['4', '8']

或者在集合理解中使用>>> def finder(s): ... seen,yields=set(),set() ... for i in s: ... if i in seen: ... if i not in yields: ... yield i ... yields.add(i) ... else : ... yields.add(i) ... else: ... seen.add(i) ... >>> list(finder(a)) ['4', '8'] 方法:

str.count

所有方法的基准,显示最后两种方式(自定义函数和集合理解比>>> set(i for i in a if a.count(i)>1) set(['8', '4']) 快得多):

Counter

结果:

from timeit import timeit


s1="""
a = "12348546478"
[i for i,j in Counter(a).items() if j>1]

"""
s2="""
def finder(s):
    seen,yields=set(),set()
    for i in s:
      if i in seen:
         if i not in yields:
            yield i
            yields.add(i)
         else :
            yields.add(i)
      else:
          seen.add(i)

a = "12348546478"
list(finder(a))

"""

s3="""
a = "12348546478"
set(i for i in a if a.count(i)>1)
"""

print '1st: ' ,timeit(stmt=s1, number=100000,setup="from collections import Counter")
print '2nd : ',timeit(stmt=s2, number=100000)
print '3rd : ',timeit(stmt=s2, number=100000)

我也尝试过长字符串(1st: 0.726881027222 2nd : 0.265578985214 3rd : 0.26243185997 )并且仍然得到相同的结果:

a = "12348546478"*10000

我的建议是使用更加pythonic的集合理解:

1st:  25.5780302721341
2nd :  11.8482989001177
3rd :  11.926538944245

答案 2 :(得分:2)

您还可以使用字典来获取唯一字符的数量,因为字典中的键始终是唯一的。

android.support.v4.app.FragmentManager 

d将包含{'1':1,'3':1,'2':1,'5':1,'4':3,'7':1,'6':1,' 8':2}

Kasramvd给出的答案是一个很好的方法。

答案 3 :(得分:1)

您可以使用下面的功能检查字符重复。如果没有重复字符,则返回True,否则返回False。

Python代码

def isThereRepitition(x):
   for char in x: #copies and iterates passing a value to char everytime
       x=x[1:] #deletes the first character in the string x
       if char in x: #checks if there is char in x string
           return False
return True

答案 4 :(得分:1)

简化@Kasravnd 第二个答案,

第一种方法:

def finder(s):
    seen,yields=set(),set()
    for i in s:
      if i not in seen:
         seen.add(i)
         
      elif i not in yields:
         yield i
         yields.add(i)
         
a = "12348546478"
print(list(finder(a)))

第二种方法

def finder(s):
    seen,yields=set(),set()
    for i in s:
      if i in seen and i not in yields:
          yield i
          yields.add(i)
      else:
          seen.add(i)
    
a = "12348546478"
print(list(finder(a)))


第三种方法

def finder(s):
    yield from {i for i, v in enumerate(s) if v in s[i+1:]}

a = "12348546478"
print(list(set(a[i] for i in finder(a))))

都产生重复的东西

['4', '8']

[Program finished]

@muddyfish 是检查是否存在重复项的最简单方法。

答案 5 :(得分:0)

import collections


 a = "12348546478"
 countOfWords = collections.Counter(a)
 result = [i for i in countOfWords if countOfWords[i]>1]
 result

尝试一下

答案 6 :(得分:0)

来自 future 的更新。 (2021 年 1 月 26 日)

出于好奇,今晚在 Python3.8 中使用 2 个更改重新运行此测试,得到了非常不同的结果:

  1. change 1- from collections import Counter # 先导入这个
  2. 更改 2 - 生成更大的数字字符串: a = "123485464781233299345355234234355234458"
results:
1st:  0.4764095
2nd :  0.6692353
3rd :  0.6512726000000002