[英]How does comparison operator affect the outcome on dictionaries? Python 3.8
我的情況與我所看到的略有不同,因此我請求一些幫助來理解。
我正在做一個問題,我需要檢查列表中的某些字符是否在字符串中。 我仍在學習過程中,所以我認為為了能夠解釋任何列表和任何字符串輸入,我應該將它們轉換為具有相同值的字典並比較兩者,因為我認為這會更容易。 我在比較部分最后被卡住了,但是當我將字典的鍵與 <= 進行比較時,它起作用了。 這是代碼,
string = 'trleba'
listofchar = ['a', 'b', 'e', 'l', 'r', 't']
def isItInIt(string, listofchar):
letters = {}
stringtoletter = {}
for c in listofchar:
if c not in letters:
letters[c] = 1
else:
letters[c] += 1
for e in list(string):
if e not in stringtoletter:
stringtoletter[e] = 1
else:
stringtoletter[e] += 1
if stringtoletter.keys() <= letters.keys():
return True
else:
return False
print(isItInIt(string, listofchar))
如果那里可能有錯誤,我很抱歉,我不得不更改一些變量名。 我的問題基本上是,<= 在這里究竟是如何工作的? 我試着把它分解並寫出來,但我似乎無法理解它。 預先感謝您的回復。
對於集合(以及類似於集合的對象,如.keys()
的結果), <=
運算符表示“子集或等於”; 數學符號是:⊆
其他比較<
, >=
, >
類似於 map 到 ⊂, ⊇ 和 ⊃ 的集合。
Documentation for set: https://docs.python.org/3/library/stdtypes.html#frozenset.issubset Documentation for dict.keys(): https://docs.python.org/3/library/stdtypes.html #dictionary-view-objects (以“Key views are set-like”開頭的段落)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.