![](/img/trans.png)
[英]How to check if a string contains a specific character or not in python
[英]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.