[英]If dict2 value = dict1 key, replace entire dict2 value with dict1 value
[英]How to compare the value of the key in Dict 1 is “==” or“!=” value of the same key in Dict2,if exists
string1 = "aadsfytggfbbhieenoohghgsfdetsuhbdfvd"
sortedstring = "".join(sorted(string1))
string2 = "dfgthhdqqaaiirrthhnnoogsfdet"
sortedstring1 = "".join(sorted(string2))
uniqueString = {}
for i in sortedstring:
if i in uniqueString:
uniqueString[i]+= 1
else:
uniqueString[i] = 1
print uniqueString
uniqueString1 = {}
for i in sortedstring1:
if i in uniqueString1:
uniqueString1[i]+= 1
else:
uniqueString1[i] = 1
print uniqueString1
它給了我這個輸出:
{'a': 2, 'b': 3, 'e': 3, 'd': 4, 'g': 4, 'f': 4, 'i': 1, 'h': 4, 'o': 2, 'n': 1, 's': 3, 'u': 1, 't': 2, 'v': 1, 'y': 1}
{'a': 2, 'e': 1, 'd': 3, 'g': 2, 'f': 2, 'i': 2, 'h': 4, 'o': 2, 'n': 2, 'q': 2, 's': 1, 'r': 2, 't': 3}
在這里,我需要的,如果“A”的值(這里是2) uniqueString
等於“A”的值(這里是2) uniqueString1
它應該返回TRUE,否則假。
我需要驗證在string1中重復x次的字符是否在string1中,並且如果在字符串2中重復相同的字符x次,則它應該返回True
否則為False
。
您正在做什么,已經在python中實現了: collections.Counter
:
from collections import Counter
string1 = "aadsfytggfbbhieenoohghgsfdetsuhbdfvd"
string2 = "dfgthhdqqaaiirrthhnnoogsfdet"
counter1 = Counter(string1)
counter2 = Counter(string2)
print(counter1)
# Counter({'f': 4, 'g': 4, 'd': 4, 'h': 4, 's': 3, 'b': 3, 'e': 3, 'o': 2,
# 't': 2, 'a': 2, 'i': 1, 'u': 1, 'n': 1, 'v': 1, 'y': 1})
print(counter2)
# Counter({'h': 4, 'd': 3, 't': 3, 'i': 2, 'f': 2, 'g': 2, 'o': 2, 'n': 2,
# 'q': 2, 'r': 2, 'a': 2, 's': 1, 'e': 1})
並通過以下方法比較它們是否相等:
print(counter1['a'] == counter2['a'])
# True
或者,如果您想要一個包含counter1
每個元素的所有檢查的字典,只需使用dict理解即可:
character_equally_often = {i: counter1[i] == counter2[i] for i in counter1}
print(character_equally_often)
# {'i': False, 'u': False, 'f': False, 'g': False, 'o': True,
# 's': False, 'd': False, 'n': False, 't': False, 'h': True,
# 'v': False, 'b': False, 'e': False, 'y': False, 'a': True}
這只是比較第一個Counter中包含的所有字符,但可以很容易地擴展為包含兩個Counter:
character_equally_often = {i: counter1[i] == counter2[i] for i in set(string1).union(set(string2))}
print(character_equally_often)
# {'i': False, 'u': False, 'f': False, 'g': False, 'o': True,
# 's': False, 'v': False, 'n': False, 't': False, 'h': True,
# 'b': False, 'e': False, 'q': False, 'r': False, 'y': False,
# 'a': True, 'd': False}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.