如何组合循环语句?

时间:2017-06-30 16:30:29

标签: python-2.7

这是我的代码示例:

list_participants = [{'Name': 'Rudi', 'Gender': 'Male', 'Age': 17},
                     {'Name': 'Ica', 'Gender': 'Female', 'Age': 18},
                     {'Name': 'Uci', 'Gender': 'Female', 'Age': 18}
                    ]

Oldest_age = 0
oldest_participant = []
male = 0
female = 0

for participant in list_participants:
  print participant
  age = participant['Age']
  if age > Oldest_age:
    Oldest_age = age

for participant in list_participants:
  name = participant['Name']
  age = participant['Age']
  if age == Oldest_age:
    oldest_participant.append(name)

for participant in list_participants:
  if participant == 'Male':
    male += 1
  elif participant == 'Female':
    female += 1

我想要一个简单的for循环,它被转换为一个for循环。我试了一次,但是有一个错误,所以输出不符合我的意愿

2 个答案:

答案 0 :(得分:0)

在一次迭代中,您可以更新最早的年龄,如果您发现年龄大于当前最大年龄,只需清除最早的参与者列表:

oldest_age = 0
oldest_participant = []
male = 0
female = 0

for participant in list_participants:
    age = participant['Age']
    name = participant['Name']
    if age > oldest_age:
        oldest_age = age  
        del oldest_participant[:]       

    if age == oldest_age:
        oldest_participant.append(name)

    if participant == 'Male':
        male += 1
    elif participant == 'Female':
        female += 1

答案 1 :(得分:0)

这就是为什么你只能让一个for循环得到你想要的输出(我也纠正了你的男性和女性数,因为我发现你没有计算它们)

代码如下:

list_participants = [{'Name': 'Rudi', 'Gender': 'Male', 'Age': 17},
                     {'Name': 'Ica', 'Gender': 'Female', 'Age': 18},
                     {'Name': 'Uci', 'Gender': 'Female', 'Age': 18}
                    ]
Oldest_age = 0
oldest_participant = []
male = 0
female = 0

for participant in list_participants:
    print participant

    age = participant['Age']
    if age > Oldest_age:
        oldest_participant = []
        Oldest_age = age

    name = participant['Name']
    age = participant['Age']
    if age == Oldest_age:
        oldest_participant.append(name)

    gender = participant['Gender']  # here this will make the count right
    if gender == 'Male':
        male += 1
    elif gender == 'Female':
        female += 1

所以如果你测试:

print Oldest_age
print oldest_participant
print male
print female

输出将是:

18
['Ica', 'Uci']
1
2

快乐编码。