繁体   English   中英

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

[英]How to check if a string contains 2 of the same character

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

我使用了适用于 6 个字符的字符串的 if 语句,但如果给定一个大字符串,这将需要很长时间。 那么我怎样才能让这段代码更有效率呢?

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 应该打印对

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

string = string[::2]

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

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

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
 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")

output

pair

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

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

output:

{'8': 2} #output of out
Pair

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM