Python入门 lab10

1 Looping over list of dictionaries

1.1 print out the first name and last name of the person

running result:

在这里插入图片描述

1.2 print_names.py

code

def print_names(people):
  # TODO: Loop over the people list
  for person in people:
    # TODO: print the first_name and last_name of the person in one line, separated by a space
    print(f"{person['first_name']} {person['last_name']}")


people = [{'first_name': 'Joe', 'last_name': 'Smith', 'age': 51, 'spouse': 'Edna'},
{'first_name': 'Edna', 'last_name': 'Smith', 'age': 48, 'spouse': 'Joe'},
{'first_name': 'Jacob', 'last_name': 'Jones', 'age': 33, 'spouse': 'Lily'},
{'first_name': 'Lily', 'last_name': 'White', 'age': 29, 'spouse': 'Jacob'},
{'first_name': 'Tiffany', 'last_name': 'Poe', 'age': 37, 'spouse': 'Sean'},
{'first_name': 'Emily', 'last_name': 'Miller', 'age': 24, 'spouse': 'Michael'},
{'first_name': 'Sean', 'last_name': 'Miller', 'age': 40, 'spouse': 'Tiffany'},
{'first_name': 'Michael', 'last_name': 'Poe', 'age': 25, 'spouse': 'Emily'}]

print_names(people)

result

running result: (the result matches the expectation)

在这里插入图片描述


2 Working with csv files

code

def total_blm_protests(states):
    # Load BLM protest data
    blm_protest_data = get_blm_data('blm_state.csv')

    total_protests = 0
    for state_data in blm_protest_data:
        if state_data['State'] in states:
            total_protests += state_data['TotalProtests']

    return int(total_protests)

test cases

# Test cases
states = ["California", "Texas"]
print(total_blm_protests(states))  # Output: 110

states = []
print(total_blm_protests(states))  # Output: 0

states = ["Alaska", "New Mexico", "Arkansas", "New York"]
print(total_blm_protests(states))  # Output: 72

result

running result:

在这里插入图片描述

  • different arguments are tried as you can see in the screenshot above
  • every result matches the expectation
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值