比较运算符如何影响字典的结果? Python 3.8
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()
的结果),<=
运算符表示“子集或等于”;数学符号为:⊆
其他比较 <
、>=
、>
类似地映射到集合的 ⊂、⊇ 和 ⊃。
集合的文档:https://docs.python.org/3/library/stdtypes.html#frozenset.issubset
dict.keys() 的文档:https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects(以“键视图类似设置”开头的段落)
dict.keys() return Dictionary view objects 这是类集合对象。
<= 等同于 issubset set 方法。
我的情况与我看到的略有不同,因此我请求一些帮助来理解。
我正在做一个问题,我需要检查列表中的某些字符是否在字符串中。 我仍在学习过程中,所以我认为为了能够解释任何列表和任何 字符串输入,我应该将它们转换为具有相同值的字典并比较两者,因为我认为这样会更容易。我最后被比较部分卡住了,但是当我将字典的键与 <= 进行比较时,它起作用了。这是代码,
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()
的结果),<=
运算符表示“子集或等于”;数学符号为:⊆
其他比较 <
、>=
、>
类似地映射到集合的 ⊂、⊇ 和 ⊃。
集合的文档:https://docs.python.org/3/library/stdtypes.html#frozenset.issubset dict.keys() 的文档:https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects(以“键视图类似设置”开头的段落)
dict.keys() return Dictionary view objects 这是类集合对象。 <= 等同于 issubset set 方法。