如何检查字符串是否包含2个相同字符

时间:2019-10-17 23:32:10

标签: python python-3.x

使用for循环,while循环和/或if语句。如何在数字为偶数的字符串中找到数字对

我使用了if语句,该语句适用于6个字符串,但是如果给出一个大字符串,它将永远占用时间。那么如何使这段代码更高效?

string = '8h8s9c'
if string[0] == string[2] or string[0] == string[4] :
   print('pair')
if string[2] == string[0] or string[2] == string[4] :
   print('pair')
else:
   print('This string contains no pair')

8h8s9c应该打印成对

5s7a5k应该打印一对

4 个答案:

答案 0 :(得分:2)

由于我们只担心偶数索引,因此我们可以立即删除所有其他字符。

string = string[::2]

然后检查我们关心的每个字符(十进制数字),然后查看它是否在其中两次。

if any(string.count(x)>1 for x in '0123456789'):print('pair')
else:print('This string contains no pair')

答案 1 :(得分:1)

python中的超级简单答案:

string = '8h8s9c'

string = string[::2]; #string = "889", this basically splices the string

string1 = list(string) #string1 = ['8','8','9'], separates into digits

string2 = set(string1) #string2 = {'9','8'} basically all duplicates get eliminated if any. therefore IF there are duplicates, number of elements WILL reduce.

print(len(string1) == len(string2)) # false as 3 != 2

答案 2 :(得分:0)

 def func(s):
      l  = list(s)
      for i in s:
           if l.count(i)>1:
                return True
      return False

s = "8h8s9c"
if func(s):
     print("pair")
else:
     print("not pair")

输出

pair

答案 3 :(得分:0)

这将为您提供包含所有配对和出现次数的字典:

Schedule[1]← {(LAR,CP), (KCC,JJ), (NYG,DC), (BB,NYJ), (CIN,SS), (DB,OR), (WR,PE),(GBP,CB), (AF,MV), (PS,NEP), (HT,NOS), (IC,LAC), (TT,CLV), (SF,TBB), (DL,AC),(BR,MD)}

Schedule[2]←{(SS,PS), (BB,NYG), (DC,WR), (SF,CIN), (IC,TT), (JJ,HT), (PE,AF), (KCC,OR),(LAC,DL), (CB,DB), (AC,BR), (NOS,LAR), (TBB,CP), (NEP,MD), (MV,GBP), (CLV,NYJ)}

输出:

from collections import Counter
counts = Counter(string)
out = {key:counts[key] for key in counts.keys() if counts[key] > 1}
if out:
    print('Pair')