【问题标题】:Reading value from file and counting the number of each status从文件中读取值并计算每个状态的数量
【发布时间】:2020-05-13 03:18:57
【问题描述】:

我有 txt 文件,它有这些 Bmi 值:

18.9
20.4
16.5
28.7
34.2
24.5
17.2
29.7
23.2

所以如果我在这里有这段代码

if ( bmi < 18.5):
   Status ="underweight"

elif ( bmi >= 18.5 and bmi < 24.5):
   Status = "normal"

elif ( bmi >= 24.5 and bmi <29.9):
   Status = "overweight "

elif ( bmi >= 30.0):
   Status = "Obesity"

现在我想根据 txt 文件中的值计算每个状态的数量,希望清楚

【问题讨论】:

    标签: python python-3.x list python-2.7 file


    【解决方案1】:

    您必须从文件中读取行,并且对于每一行,将该行转换为浮点数,进行检查,然后添加到计数器变量中。

    (将values.txt 替换为您的文件路径)

    with open("values.txt") as f:
        lines = f.readlines()
    
        underweight = 0
        normal = 0
        overweight = 0
        obese = 0
    
        for line in lines:
            bmi = float(line)
    
            if ( bmi < 18.5): 
                underweight += 1
            elif ( bmi >= 18.5 and bmi < 24.5):
                underweight += 1
            elif ( bmi >= 24.5 and bmi <29.9):
                overweight += 1
            elif ( bmi >= 30.0):
                obese += 1
    

    然后您可以像任何其他变量一样打印出underweight 和您的其他变量:

    print(underweight)
    print(normal)
    print(overweight)
    print(obese)
    

    【讨论】:

      【解决方案2】:

      使用您现有的代码,您可以创建一个函数来返回 BMI 状态:

      def get_bmi_status(bmi):
          if bmi < 18.5: 
              return "underweight"
      
          elif bmi >= 18.5 and bmi < 24.5: 
              return "normal"
      
          elif bmi >= 24.5 and bmi < 29.9: 
              return "overweight"
      
          elif bmi >= 30.0: 
              return "Obesity"
      

      然后您可以逐行读取文件,转换为float,然后将计数收集到collections.defaultdict

      from collections import defaultdict
      
      with open("data.txt") as f:
          counts = defaultdict(int)
          for bmi in f:
              status = get_bmi_status(float(bmi.strip()))
              counts[status] += 1
      
          print(counts)
      

      这会给你这些计数:

      defaultdict(<class 'int'>, {'normal': 3, 'underweight': 2, 'overweight': 3, 'Obesity': 1})
      

      我们也可以通过collections.Counter 获得计数:

      from collections import Counter
      
      with open("data.txt") as f:
          counts = Counter(get_bmi_status(float(bmi.strip())) for bmi in f)
          print(counts)
      

      哪个会代替:

      Counter({'normal': 3, 'overweight': 3, 'underweight': 2, 'Obesity': 1})
      

      defaultdictCounter 都是dict 的子类,因此您可以像使用普通字典一样使用它们。

      【讨论】:

        最近更新 更多