【问题标题】:How can it search inside the dictionary, if the dictionary is empty?如果字典为空,它如何在字典中搜索?
【发布时间】:2019-01-23 18:05:14
【问题描述】:

我刚开始学习python,发现了这个sn-p。它应该计算一个单词出现的次数。我想,对你们所有人来说,这似乎很合乎逻辑,但不幸的是,对我来说,这没有任何意义。

str = "house is where you live, you don't leave the house."
dict = {}
list = str.split(" ") 
for word in list:  # Loop over the list
    if word in dict:  # How can I loop over the dictionary if it's empty?
        dict[word] = dict[word] + 1
    else:
        dict[word] = 1

所以,我的问题是,我怎样才能遍历字典?字典不应该是空的,因为我没有在里面传递任何东西吗? 也许我不够聪明,但我看不到逻辑。谁能解释一下它是如何工作的? 非常感谢

【问题讨论】:

  • 循环运行时,字典被“填充”。它只是第一次通过时是空的。此外,永远不要使用关键字作为变量名。 str、dict 和 list 在这里被覆盖。
  • 您使用if word in dict: 添加了关于循环的评论。 if 语句不是循环。
  • (不管怎样,循环一个空集合是完全没问题的,就像将数字乘以 0 完全没问题一样。)
  • @ParitoshSingh - strdictlist 不是关键字;它们只是内置函数。如果它们是关键字,则在尝试分配给它们时会出错。这就是为什么在考虑名称时需要谨慎:它不会自动为您捕捉到。
  • 谢谢大家的意见。我从你那里学到了更多,我自己专注于这段代码一个多小时。

标签: python python-3.x dictionary for-loop


【解决方案1】:

正如其他人指出的那样,术语 strdictlist 不应该用于变量名,因为这些是在 Python 中执行特殊操作的实际 Python 命令。例如,str(33) 将数字 33 转换为字符串“33”。诚然,Python 通常足够聪明,可以理解您想将这些东西用作变量名,但为了避免混淆,您确实应该使用其他东西。所以这里是相同的代码,不同的变量名,加上循环末尾的一些print 语句:

mystring = "house is where you live, you don't leave the house."
mydict = {}
mylist = mystring.split(" ") 
for word in mylist:  # Loop over the list
    if word in mydict:  
        mydict[word] = mydict[word] + 1
    else:
        mydict[word] = 1
    print("\nmydict is now:")
    print(mydict)

如果你运行它,你会得到以下输出:

mydict is now:
{'house': 1}

mydict is now:
{'house': 1, 'is': 1}

mydict is now:
{'house': 1, 'is': 1, 'where': 1}

mydict is now:
{'house': 1, 'is': 1, 'where': 1, 'you': 1}

mydict is now:
{'house': 1, 'is': 1, 'live,': 1, 'where': 1, 'you': 1}

mydict is now:
{'house': 1, 'is': 1, 'live,': 1, 'where': 1, 'you': 2}

mydict is now:
{"don't": 1, 'house': 1, 'is': 1, 'live,': 1, 'you': 2, 'where': 1}

mydict is now:
{"don't": 1, 'house': 1, 'is': 1, 'live,': 1, 'leave': 1, 'you': 2, 'where': 1}

mydict is now:
{"don't": 1, 'house': 1, 'is': 1, 'live,': 1, 'leave': 1, 'you': 2, 'where': 1, 'the': 1}

mydict is now:
{"don't": 1, 'house': 1, 'is': 1, 'live,': 1, 'house.': 1, 'leave': 1, 'you': 2, 'where': 1, 'the': 1}

所以mydict 确实在更新它找到的每个单词。这也应该让您更好地了解字典在 Python 中是如何工作的。

要清楚,您不是在“循环”字典。 for 命令启动一个循环; if word in mydict: 命令不是循环,而只是比较。它查看mydict 中的所有键,并查看是否有一个与word 匹配的字符串。

另外,请注意,由于您只将句子拆分为字符串,因此您的单词列表包括 "house""house."。由于这两个不完全匹配,它们被视为两个不同的词,这就是为什么您在字典中看到 'house': 1'house.': 1 而不是 'house': 2

【讨论】:

  • 不客气!是的,我也不知道为什么我被否决了,更不用说至少两次了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-29
相关资源
最近更新 更多