python学习笔记-列表,字典,以及函数返回值

1、作业题-列出下面图片中的属性

 

 

列表+字典,如下面的 shopping_man 

# 符号后面加空格
shopping_man = [
    {"name": "John", "age": 20, "country": "USA", "sex": "male", "height": 185, "weight": 65},
    {"name": "Tom", "age": 25, "country": "China", "sex": "female", "height": 165, "weight": 55},
    {"name": "dick", "age": 15, "country": "USA", "sex": "male", "height": 175, "weight": 75},
    {"name": "Lucy", "age": 45, "country": "Japan", "sex": "female", "height": 168, "weight": 45},
    {"name": "David", "age": 35, "country": "USA", "sex": "male", "height": 176, "weight": 65},
    {"name": "Bill", "age": 28, "country": "England", "sex": "male", "height": 170, "weight": 60},
    {"name": "Me", "age": 25, "country": "China", "sex": "female", "height" : 163, "weight": 45}
]


2、遍历列表的两种方法-一种可以多获取索引,方便以后要用

方式一:按小编来遍历,通过下标来获取元素;

for index in range(列表长度):

    每个元素都要做的事

index就是下标

取值方法:列表变量名[index]

 

方式二:直接遍历其中的值,直接获取元素

for item in 列表变量名:

    每个元素都要做的事

item就是列表中的元素

 

# 查找年龄大于20,或者 女性且身高160以上,获取名字
# for循环,遍历下标,通过下标获取遍历
for index in range(0, len(shopping_man)):
    if shopping_man[index]["age"] > 20 or (shopping_man[index]["sex"] == "female" and shopping_man[index]["height"] > 160):
        print(index, shopping_man[index]["name"])

# for循环,遍历列表的值,直接取值
for item in shopping_man:
    if item["age"] > 20 or (item["sex"] == "female" and item["height"] > 160):
        print(item["name"])

3、字典的遍历

person_info_dict = {"name": "Me", "age": 25, "country": "China", "sex": "female", "height" : 163, "weight": 45}


# dict通过键名获取值
# key是name,age等字段,然后输出的是me,25等值
for key in person_info_dict.keys():
    print(person_info_dict[key])

# 遍历 key,value
for key, value in person_info_dict.items():
    print(key, value)

4、函数返回值

函数返回值和返回值引用注意:

返回变量:函数atm  return bank_id, money

调用则使用两个变量: bbb, mmm = atm(XXX),来获取返回值bank_id, money

 

返回字典:函数atm  return { “bank_id”: bank_id, “money”: money }

调用则 dictA = atm(XXX)

 

posted @ 2020-03-17 22:48  依羽杉  阅读(477)  评论(0编辑  收藏  举报