设计一个数据结构,存储班级中所有同学的本学期五门课程的成绩信息 , 包含三个元素,分别是学号,姓名,成绩。 设计出该结构进行存储,为了简化,学号为1~100, 学号为1的同学姓名为 “A1”, 学号为30的同学姓名为”A30”,每个同学每门课程的成绩均为随机生成的一个60~100之间的随机数。 (1)当结构为dic = {1:[“A1”,[60,60,60,60,60 ]]}时,【不使用序列化方法】 ①把如上数据写入名字为score.txt的文件中。以字符串形式写入。 ②读出score.txt文件中的内容到内存中,并使用循环对读出的字典进行控制台输出。 (2)当结构为[ {1:{ “A1”:[ 60,60,60,60,60]} }, {2:{“A2”:[ 60,60,60,60,60]} }……] 【不使用序列化方法】 ①把如上数据写入名字为score.txt的文件中。以字符串形式写入。 ②读出score.txt文件中的内容到内存中,并使用循环对读出的内容进行控制台输出。 ③使用序列化的方法,分别把(1)和(2)的内容写入文件,然后再从文件中读出。
时间: 2024-02-28 19:57:38 浏览: 73
(1) 不使用序列化方法:
①写入文件:
```python
import random
# 生成数据
data = {}
for i in range(1, 101):
name = "A" + str(i)
scores = [random.randint(60, 100) for _ in range(5)]
data[i] = [name, scores]
# 写入文件
with open("score.txt", "w") as f:
for key, value in data.items():
line = str(key) + ":" + str(value[0]) + "," + ",".join(str(x) for x in value[1]) + "\n"
f.write(line)
```
②读出文件:
```python
# 读出文件
with open("score.txt", "r") as f:
for line in f:
line = line.strip()
if line:
parts = line.split(":")
key = int(parts[0])
value = parts[1].split(",")
name = value[0]
scores = [int(x) for x in value[1:]]
print(key, name, scores)
```
(2) 不使用序列化方法:
①写入文件:
```python
import random
# 生成数据
data = []
for i in range(1, 101):
name = "A" + str(i)
scores = [random.randint(60, 100) for _ in range(5)]
item = {i: {name: scores}}
data.append(item)
# 写入文件
with open("score.txt", "w") as f:
for item in data:
for key, value in item.items():
line = str(key) + ":" + str(value) + "\n"
f.write(line)
```
②读出文件:
```python
# 读出文件
with open("score.txt", "r") as f:
for line in f:
line = line.strip()
if line:
parts = line.split(":")
key = int(parts[0])
value = eval(parts[1])
name, scores = list(value.items())[0]
print(key, name, scores)
```
③使用序列化方法:
```python
import random
import pickle
# 生成数据
data1 = {}
for i in range(1, 101):
name = "A" + str(i)
scores = [random.randint(60, 100) for _ in range(5)]
data1[i] = [name, scores]
data2 = []
for i in range(1, 101):
name = "A" + str(i)
scores = [random.randint(60, 100) for _ in range(5)]
item = {i: {name: scores}}
data2.append(item)
# 序列化并写入文件
with open("score1.bin", "wb") as f:
pickle.dump(data1, f)
with open("score2.bin", "wb") as f:
pickle.dump(data2, f)
# 读出并反序列化
with open("score1.bin", "rb") as f:
data1 = pickle.load(f)
for key, value in data1.items():
print(key, value[0], value[1])
with open("score2.bin", "rb") as f:
data2 = pickle.load(f)
for item in data2:
for key, value in item.items():
name, scores = list(value.items())[0]
print(key, name, scores)
```
阅读全文