【问题标题】:counting values in a dictionary Python3在字典Python3中计算值
【发布时间】:2021-06-03 20:35:50
【问题描述】:
a = {bob:home, amy:school, george:school, Noah:school, Lilian:home}

我正在尝试获取此输出:

待在家里的人数是 2

上学人数为 3

请帮忙

def counting(x):
  homecount: 0
  schoolcount: 0
for i in x.key:
   if i == home:
    homecount += 1
   else:
    schoolcount +=1
print (f' number of people staying home is {homecount} ')
print(f' number of people going to school is {schoolcount}')

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我刚刚编辑并添加了我的代码
  • for i in x.values(): 将帮助您修复代码。
  • 非常感谢您现在就尝试!
  • 还有其他错误:homecount: 0 应该是homecount = 0schoolcount 也一样。此外,home 是一个字符串,应该用引号引起来,除非您在别处定义了变量 home

标签: python-3.x list dictionary


【解决方案1】:

您的代码存在几个问题,包括某些语法不是有效的 Python。

def counting(x):
    homecount = 0
    schoolcount = 0
    for val in x.values():
        if val == "home":
            homecount += 1
        elif val == "school":
            schoolcount += 1
        else:
            continue
    print(f"The number of people staying home is {homecount}")
    print(f"The number of people going to school is {schoolcount}")

counting(a)
The number of people staying home is 2
The number of people going to school is 3
  1. 要声明变量,请使用= 而不是:
  2. 您想迭代 values 而不是 keys
  3. 在您的情况下比较值的相等性时,您必须使用“home”作为字符串,而不是文字变量。
  4. 在这种情况下不要使用没有elifelse,因为如果字典中包含homeschool 之外的值,您可能会得到错误的计数。

【讨论】:

  • 请问为什么在此处添加 else 语句很重要?它总是让我感到困惑
  • 因为如果value 不是"home""school",我们希望继续循环而不做任何其他事情。我们不能总是确定数据将包含这两个值
  • 您可以删除else: continue。这里不需要。
  • 哦,很有意义!非常感谢你们,你们非常乐于助人
  • @JohnnyMopp 这不是必需的,但对于初学者来说,最好是 verbose 以便他们理解/学习。一旦掌握得更好,他们可以在未来走捷径
【解决方案2】:

答案可以用总和来表示。

home_sum = sum([x=="home" for x in a.values()])
school_sum = sum([x=="school" for x in a.values()])

【讨论】:

    【解决方案3】:

    其他答案很好,但您可能还想查看collections.Counter,因为它在这样的情况下为您做了很多工作:

    import collections
    
    data = {"bob":"home", "amy":"school", "george":"school", "Noah":"school", "Lilian":"home"}
    the_count = collections.Counter(data.values())
    
    print(f'staying home: { the_count.get("home") }')
    print(f'going to school: { the_count.get("school") }')
    

    给你:

    staying home: 2
    going to school: 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多