網(wǎng)站首頁 編程語言 正文
python兩字符串映射
題目:
pattern = "abba",s="dog cat cat dog"---->True
pattern = "abba",s="dog cat cat fish"----->False
class Solution:
def is_pattern_matched(self, pattern:str,s: str) -> bool:
pattern = list(''.join(pattern))
s = s.split(" ")
a = {}
for i in range(len(pattern)):
a.update({pattern[i]:s[i]})#update() 方法用于修改/更新當(dāng)前集合/字典,可以添加新的元素或集合到當(dāng)前集合中,如果添加的元素在集合中已存在,則該元素只會出現(xiàn)一次,重復(fù)的會忽略。
# a = zip(pattern,s)
# a = dict(a)
for j in range(len(pattern)):
if s[j] != a[pattern[j]]:
return False
else:
return True
pattern = "abba"
s = "dog cat cat dog"
S = Solution()
result = S.is_pattern_matched(pattern,s)
print(result)
python字符映射表和字符替換
python中有一個內(nèi)建函數(shù)maketrans()可以對兩個字符串進行字符映射,創(chuàng)建出映射表。
結(jié)構(gòu)如下:
str.maketrans(intab,outtab)
當(dāng)使用該函數(shù)時,將會把intab中的字符串對out字符串中的字符進行一一對應(yīng)。
而使用translate()函數(shù)則可以利用映射表字符對指定字符串的字符進行替換。
結(jié)構(gòu)如下:
str.translate(table)
示例:
str1="abcdefghijklmnopqrstuvwxyz"
str2="qwertyuiopasdfghjklzxcvbnm"
table=str.maketrans(str1,str2)
str="sword art online"
print(str.translate(table))#==>lvgkr qkz gfsoft
上面的例子使用了這兩個函數(shù)寫了一個簡單的加密程序。其中str1是函數(shù)str.maketrans(intab,outtab)中的intab,而str2是str.maketrans(intab,outtab)中的outtab。
不過這種加密方法有一個問題。就是intab與outtab所代表的的字符串的長度必須一致,且各自的字符串中的字符必須唯一,否則解密時容易出錯。
示例:
str1="abcdefghijklmnopqrstuvwxyz"
str2="qwertyuiopasdfghjklzxcvbnm"
table1=str.maketrans(str1,str2)
table1_1=str.maketrans(str2,str1)
str="sword art online"
jiami=str.translate(table1)
jiemi=jiami.translate(table1_1)
print(jiami)#==>lvgkr qkz gfsoft
print(jiemi)#==>sword art online
原文鏈接:https://blog.csdn.net/weixin_42698464/article/details/122661481
相關(guān)推薦
- 2022-04-05 如何定義多個context:property-placeholder配置
- 2022-08-02 pyspark自定義UDAF函數(shù)調(diào)用報錯問題解決_python
- 2022-12-14 C++?Boost?PointerContainer智能指針詳解_C 語言
- 2022-07-06 C語言舉例講解轉(zhuǎn)義字符的使用_C 語言
- 2022-12-15 Pytorch加載數(shù)據(jù)集的方式總結(jié)及補充_python
- 2022-10-18 react父組件調(diào)用子組件的方式匯總_React
- 2022-02-02 怎么樣判斷頁面是否在iframe框架里
- 2023-03-28 Python使用機器學(xué)習(xí)模型實現(xiàn)溫度預(yù)測詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支