加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
step1_record_1_list.py 1.55 KB
一键复制 编辑 原始数据 按行查看 历史
goodfeng 提交于 2023-10-03 12:41 . 从列表到字典
# coding:utf-8
'''
列表数据库
'''
# 使用列表list来表示数据
bob = ['陈小山',21,'男','22软件3+2']
sue = ['麦海丽',20,'女','22软件3+2']
# # 获取二人的姓名和年龄
# name = bob[0]
# age = bob[1]
# print(name,age)
# # 增加年龄
# bob[1]+=1
# print(bob)
# 构造数据库database,命名为people
people = [bob,sue]
for person in people:
print(person)
# 新增一个人的记录(record)
tom = ['陈彬',22,'男','22软件3+2']
people.append(tom)
# 获取平均年龄
ages = [person[1] for person in people]
print(ages)
import numpy as np
avg_ages = np.mean(ages)
print(avg_ages)
# 给字段(Field)加标签
NAME,AGE,GENDER,CLASSNAME = 0,1,2,3 # range(4)
# 获取花名册
namelist = [person[NAME] for person in people]
print(namelist)
# 让值与字段名成对出现,避免数据格式变化
bob = [
['NAME','陈小山'],
['AGE',21],
['GENDER','男'],
['CLASSNAME','22软件3+2']
]
sue = [
['NAME','麦海丽'],
['AGE',20],
['GENDER','女'],
['CLASSNAME','22软件3+2']
]
people = [bob,sue]
for filed,value in bob:
print(filed,value)
# 如何获取花名册
namelist = []
for person in people:
for filed,value in person:
if filed == 'NAME':
namelist.append(value)
break
print(namelist)
# 获取任意字段
def field(record,label):
for filed,value in record:
if filed == label:
return value
fileds = []
for person in people:
fileds.append(field(person,'AGE')) # person['AGE'] => 字典dict
print(fileds)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化