【问题标题】:How to count number of a specific item in list? Python3如何计算列表中特定项目的数量? Python3
【发布时间】:2021-01-17 20:50:26
【问题描述】:

下面的代码将允许用户在列表中输入指定数量的人。每个人都有三个属性:姓名、性别和年龄。代码应该计算列表中“m”字符的数量并计算列表中“f”字符的数量,但是当你到达计数行时会出错。我该如何解决这个问题?

    list1 = []
    person = dict()
    n = int(input("Enter number of elements: "))
    for i in range(0, n):
        print ("Enter information :")
        person[i] = input("Enter name: "), input("Enter sex (m or f): "), input("Enter age: ")
        list1.append(person[i])
        i = i + 1
    print (list1)
    print ("Number of males = " + list1.count('m'))
    print ("Number of females = " + list1.count('f'))

【问题讨论】:

  • 这个列表对我来说就像一个元组列表。有人,如果我错了,请纠正我。考虑到这一点,您的代码仍然有效吗?
  • stackoverflow.com/questions/16013485/… 在这里可能会有所帮助

标签: python list count


【解决方案1】:

试试这个:

print("Number of males = " + str([i[1] for i in list1].count("m")))
print("Number of females = " + str([i[1] for i in list1].count('f')))

【讨论】:

    【解决方案2】:

    或者,您可以使用默认模块 «collections» 中的计数器

    from collections import Counter
    
    li = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4,]
    
    Counter(li)
    

    这会输出Counter({1: 1, 2: 2, 3: 3, 4: 4})。计数器输出是 dict,但是,您可以更新它或选择最常见的项目。

    【讨论】:

      【解决方案3】:

      这里有几个问题:

      • 第二条print 指令引发以下错误TypeError: can only concatenate str (not "int") to str。这是因为您试图连接一个整数和一个字符串。为此,您应该将整数转换为字符串,例如:print ("Number of males = " + str(list1.count('m')))

      • 无论用户输入什么,list1.count('m') 始终为 0,因为 list1 包含元组,而您正在查找字符串的计数。你可以通过一个简单的循环得到一个只包含性别的列表:[i[1] for i in list1]

      固定代码

      list1 = []
      person = dict()
      n = int(input("Enter number of elements: "))
      for i in range(0, n):
          print ("Enter information :")
          person[i] = input("Enter name: "), input("Enter sex (m or f): "), input("Enter age: ")
          list1.append(person[i])
          i = i + 1
      print (list1)
      genders=[i[1] for i in list1]
      print("Number of males = " + str(genders.count("m")))
      print("Number of females = " + str(genders.count('f')))
      

      【讨论】:

      • 与其建立一个列表只是在你调用一次 count 后将其丢弃,你应该考虑保留对它的引用(因为你有两件事要计算)或直接计算, 没有列表。 sum(i[1] == 'm' for i in list1) 可以工作(因为 bool 对象也是整数)。 collections.counter 类型也可能值得使用,带有生成器表达式,因为这样可以轻松获取 'm''f'' 的计数。
      • 是的,当然,我这样做只是为了让逻辑看起来更清晰。
      【解决方案4】:

      使用collections.Counter 对对象进行计数。我还稍微重构了您的代码以达到您的预期:

      from collections import Counter
      people = []
      n = int(input("Enter number of people: "))
      for i in range(0, n):
          print ("Enter information:")
          person = (input("Enter name: "),
                    input("Enter sex (m or f): "),
                    int(input("Enter age: ")))
          people.append(person)
      print (people)
      c = Counter([p[1] for p in people])
      print ("Number of males = " + str(c['m']))
      print ("Number of females = " + str(c['f']))
      

      以下是一些 cmets 以及改进代码的建议:

      # make variable name more descriptive, for example users or people:
      list1 = []
      
      # no need for defining it here, abd BTW it is a tuple later, not dict:
      person = dict()
      
      # elements should be more descriptive, for example users or people:
      n = int(input("Enter number of elements: "))
      for i in range(0, n):
          print ("Enter information :")
          # Add int conversion to age: 'int(input("Enter age: "))'.
          # Also, person[i] should just one person (a single tuple)
          person[i] = input("Enter name: "), input("Enter sex (m or f): "), input("Enter age: ")
          list1.append(person[i])
          # no need for this, since i is incremented in the statement: 'for i in range(0, n)'
          i = i + 1
      print (list1)
      
      # Use collections.Counter instead.
      # Also count the second element of each element of the list.
      print ("Number of males = " + list1.count('m'))
      print ("Number of females = " + list1.count('f'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-15
        • 2023-03-23
        • 1970-01-01
        • 2017-07-21
        • 1970-01-01
        • 2021-07-16
        相关资源
        最近更新 更多