【问题标题】:Using string values in a list as integers and displaying them使用列表中的字符串值作为整数并显示它们
【发布时间】:2021-03-15 18:20:44
【问题描述】:

有一个名为 Population 的类,它以字符串值的形式包含所有人(样本人口)的年龄。我必须创建一个函数来显示有多少百分比的人落入特定年龄区间。例如,如果列表是 ["25","67","37","23","25","19","46","50"],则函数 info执行info(population)时应显示每个年龄段的人数百分比:

Number of people #8
<20's: 12.5%
20's: 37.5%
30's: 12.5%
40's: 12.5%
50's: 12.5%
more than 60's: 12.5%

Mean age: 

我在尝试使用字符串形式的数字并将它们计数为 int 时遇到了困难。我如何继续前进,我很困惑。我也不能使用理解列表来完成这项任务。

代码必须遵循:

class Population:
    def __init__(self,age=None):
        self.age=age

p = Population()
p.age = [25,36]

def info(population):
    ???

info(p)

【问题讨论】:

  • 遍历列表,保留一个计数器,其中年龄在该范围内,然后返回counter / len(population)。要将字符串转换为整数,只需执行int(string)

标签: python python-3.x list python-requests


【解决方案1】:

如果您使用字典进行跟踪,则无需将年龄更改为整数。试试这个,看看它是否符合您的要求。

class Population:
    def __init__ (self, age_list = None) :
        self.age_list = age_list
        self.mean_dictionary = {
                '10': 0,
                "20": 0,
                "30": 0,
                "40": 0,
                "50": 0,
                "60": 0,
                "70": 0,
                "80": 0,
                "90": 0}
        self.show_information ()

    def show_information (self) :
        total = 0
        for age in self.age_list :
            key = str (age [0]) + '0' 
            self.mean_dictionary [key] += 1
            total += 1

        print (f"\nNumber of people {len (self.age_list)}")
        over_60_total = 0
        for age_group, count  in self.mean_dictionary.items () :
            percent = 100 * float (count) / float (total)
            if age_group <= '50' :
                print (f"{age_group}'s:  {percent}%")
            else :
                over_60_total += count
        percent = 100 * float (over_60_total) / float (total)
        print (f'60 and over: {percent}%')

p = Population (["25","67","37","23","25","19","46","50"])

【讨论】:

    【解决方案2】:
    def info(population):
        int_ages = list(map(lambda age: int(age), population))
        return int_ages
    

    这是一种将列表中的所有字符串值转换为整数的简单方法,以便您可以使用它们来计算百分比。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多