Python 如何从字典中得到一个只有男人才有的高度

Python 如何从字典中得到一个只有男人才有的高度,python,dictionary,for-loop,Python,Dictionary,For Loop,我在写python程序。我写了一本有名字、性别和身高的字典: persons = [ ('Julie', 'female', 172), ('Lucca', 'male', 190), ('Vera', 'female', 165), ('Mike', 'male', 183), ('Ann', 'female', 150), ('Teo', 'male', 179) ] 我写信是为了打印出身高超过180的男人的名字: for i in persons: name, gender, heigh

我在写python程序。我写了一本有名字、性别和身高的字典:

persons = [
('Julie', 'female', 172),
('Lucca', 'male', 190),
('Vera', 'female', 165),
('Mike', 'male', 183),
('Ann', 'female', 150),
('Teo', 'male', 179)
]
我写信是为了打印出身高超过180的男人的名字:

for i in persons:
name, gender, height = i
if gender == 'male':
    if height > 180:
        print(name)
现在我想计算所有男人的平均身高,不包括女人。我尝试了这个,但我得到了错误的答案:

sum = 0
for i in persons:
    name, gender, height = i
    sum += height
    if gender == 'male':
        average = sum/3
print(average)
我打错号码了,输出应该是:184 还有,我怎样才能用男人的数量来代替3号呢?我的意思是程序会自动知道字典里有3个男性

average = sum/3

由于您只需要所有男性的平均值,因此仅当此人为男性时,您需要将总和相加,并让计数器运行,以便您可以动态计算平均值

persons = [
('Julie', 'female', 172),
('Lucca', 'male', 190),
('Vera', 'female', 165),
('Mike', 'male', 183),
('Ann', 'female', 150),
('Teo', 'male', 179)
]
vsota = 0
povprecje_m = 0
countr = 0
for i in persons:
    ime, spol, visina = i
    
    if spol == 'male':
      vsota += visina
      countr = countr +1
povprecje_m = vsota/countr
print(povprecje_m)
print()

我不确定底部代码示例中的语言是什么,但我用自己的变量重新编写了代码,并使其正常工作。你的原稿有几个问题

例如:

   vsota = 0
for i in osebe:
    ime, spol, visina = i
    vsota += visina
    if spol == 'M':
        povprecje_m = vsota/3
print(povprecje_m)
print()
其中:vsota是一个整数,visina是一个字符串。另外,在你确定这个人是否是男性之前,你要加上我假设的身高。如果此人是男性,则只需增加计数即可解决此问题。这只是一个配售问题。以下是修复方法:

height_count = 0
for i in persons:
    name, gender, height = i
    if gender == 'male':
        height_count += float(height)

povprecje_m = height_count/3

print(povprecje_m)
要使平均值动态,您只需添加一个计数器来跟踪IF语句的执行次数。这可以通过以下方式实现:

complete_counter = 0
height_count = 0
for i in persons:
    name, gender, height = i
    if gender == 'male':
        height_count += float(height)
        complete_counter += 1

povprecje_m = height_count/complete_counter

print(povprecje_m)
您可以使用statistics.mean为您执行此操作:

进口统计 人员=[ “朱莉”,“女”,172, 卢卡,男,190, “维拉”,“女”,165, “迈克”,“男”,183, “安”,“女”,150, "Teo","男",179岁 ] printstatistics.Mean身高,性别,如果性别=‘男性’ 输出:

184

如果您熟悉列表,请使用列表理解

# Generate list of male heights
male_heights = [height for name, sex, height in persons if sex == 'male']

# Avg is sum/number (number of male heights)
avg = sum(male_heights)/len(male_heights)
# Out: 184.0

如果spol='M',如果spol='male',这应该是吗?1 persons不是字典,而是元组列表。修正你的缩进。对不起,我忘了改名字,因为我是用我的语言做的。我会编辑这篇文章。谢谢你提醒我!计算平均值时,您需要除以一次。你的代码每次发现一个男性时都会进行除法,以计算平均值,在循环中计算男性的数量,并保持其身高的总和。循环结束后,您可以计算平均高度。为什么要将高度转换为浮点?所有高度值都是整数。我真的很抱歉,因为我忘了将名称更改为英文。非常感谢你的努力和帮助!!我把它修好了,现在我得到了正确的答案:谢谢你!!我很抱歉,因为我忘了把名字改成英文。谢谢你的努力和帮助@sancika2605别忘了做!再次感谢!非常感谢你!非常感谢你@sancika2605:见