八年级上册¶

第一单元 用计算机程序解决问题¶

第1节 处理批量数据¶

一、列表基础¶

建议使用工具 https://pythontutor.com/visualize.html#mode=edit 来可视化教学.
也可本地化布置,需要安装bottle模块在终端执行。

cd ./OnlinePythonTutor/v5-unity/
call python bottle_server.py

在浏览器地址栏输入: http://localhost:8003/live.html

In [9]:
# 1.认识列表
names = ['小林', '张三', '李四', '小明']
print(len(names))
print(names)
3
['小林', '张三', '李四小明']
In [12]:
# 2.访问列表
names = ['小林', '张三', '李四', '小明']
print(names[0])
print(names[3], names[-1])
print('你好,{}!'.format(names[1]))
print('你好,{}!'.format(names[2]))
小林
小明 小明
你好,张三!
你好,李四!
In [14]:
# 3.维护列表
# (1)修改
names = ['小林', '张三', '李四', '小明']
names[0] = '小王'
print(names[0])
# (2)添加-追加
names.append('小杨')
print(names)
小王
['小王', '张三', '李四', '小明', '小杨']
In [13]:
# 添加-插入
names = ['小林', '张三', '李四', '小明']
names.insert(0, '小杨')
print(names)
['小杨', '小林', '张三', '李四', '小明']
In [17]:
# (3)删除
names = ['小王', '张三', '李四', '小明', '小杨']
del names[0]
print(names)
name1 = names.pop()
print(names)
name2 = names.pop(2)
print(names)
print(name1, name2)
['张三', '李四', '小明', '小杨']
['张三', '李四', '小明']
['张三', '李四']
小杨 小明
In [18]:
# 拓展阅读-类、对象和方法
help(list.pop)
Help on method_descriptor:

pop(self, index=-1, /)
    Remove and return item at index (default last).
    
    Raises IndexError if list is empty or index is out of range.

In [21]:
lst = list()
lst.append('1')
lst.pop()  # 课本语句lst.pop(1)会出错
print(lst.__doc__)
Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.

体验活动:完善受邀人员管理程序¶

In [29]:
# 受邀人员管理程序
menu = '''受邀人员管理程序\n
1.查看名单 2.删除人员 3.增加人员 4.修改人员 5.退出
请选择(1-5):'''
names = ['小王', '张三', '李四', '小明', '小杨']
while True:
    c = int(input(menu))
    if c == 1:
        print('编号  姓名')
        for i in range(len(names)):
            print('{}  =>  {}'.format(i, names[i]))
    elif c == 2:
        n = int(input('请输入要删除的人员编号:'))
        del names[n]
        print('已删除编号为{}的人员'.format(n))
    elif c == 3:
        print('待开放')
        # 参考代码:
        # name = input('请输入要增加的人员姓名:')
        # names.append(name)
        # print('{}已增加'.format(name))
    elif c == 4:
        print('待开放')
        # 参考代码:
        # n = int(input('请输入要修改的人员编号:'))
        # name = input('你要把{}修改为:'.format(names[n]))
        # names[n] = name
        # print('已修改完成!')        
    elif c == 5:
        break
    
print('再见!')
受邀人员管理程序

1.查看名单 2.删除人员 3.增加人员 4.修改人员 5.退出
请选择(1-5):5
再见!

二、组织基础¶

In [30]:
# 1. 将字符串转换成数值列表
# 78.5 77.3 79.1 78.0 77.0
lst1 = input('请输入评委得分,以空格分开:')
lst1 = lst1.split()
print(lst1)

for i in range(5):
    lst1[i] = float(lst1[i])
print(lst1)
请输入评委得分,以空格分开78.5 77.3 79.1 78.0 77.0
['78.5', '77.3', '79.1', '78.0', '77.0']
[78.5, 77.3, 79.1, 78.0, 77.0]
In [31]:
lst1 = ['78.5', '77.3', '79.1', '78.0', '77.0']
lst2 = []
for i in range(5):
    lst2.append(float(lst1[i]))
print(lst2)
[78.5, 77.3, 79.1, 78.0, 77.0]
In [39]:
lst1 = ['78.5', '77.3', '79.1', '78.0', '77.0']
result = map(float, lst1)
lst1 = list(result)
print(lst1)
[78.5, 77.3, 79.1, 78.0, 77.0]
In [34]:
# 2.排序操作
lst1 = [78.5, 77.3, 79.1, 78.0, 77.0]
lst1.sort(reverse=True)
mx = lst1[0]
mn = lst1[-1]
print('最高分{},最低分{}。'.format(mx, mn))
最高分79.1,最低分77.0。
In [35]:
# 拓展阅计 sorted()函数
lst1 = [78.5, 77.3, 79.1, 78.0, 77.0]
print(sorted(lst1))
print(lst1)
lst2 = sorted(lst1, reverse=True)
mx = lst2[0]
mn = lst2[-1]
print('最高分{},最低分{}。'.format(mx, mn))
[77.0, 77.3, 78.0, 78.5, 79.1]
[78.5, 77.3, 79.1, 78.0, 77.0]
最高分79.1,最低分77.0。

实践活动:设计现场赛计分程序¶

In [58]:
# 参考程序
lst1 = []  # 各选手的评委原始得分的列表(备用)
lst2 = []  # 最终得分列表
num = 0  # 选手编号
# 选手得分输入并计分
while True:
    print('现场赛计分程序')
    s = input('请输入{}号选手的评委得分,以空格分开(q或Q退出):'.format(num))
    if s == 'Q' or s == 'q':
        break
    tmp = list(map(float, s.split()))
    # 最高分与最低分
    tmp1 = sorted(tmp)
    num2 = len(tmp1)  # 评委数
    mn, mx = tmp1[0], tmp1[-1]
    avg = (sum(tmp1) - mn - mx) / (num2 - 2)  # 平均分
    avg = round(avg, 2)  # 取2位小数
    print('{}号选手最终得分为{}。'.format(num, avg))
    lst1.append(tmp)
    lst2.append(avg)
    num = num + 1
print('比赛结束!')

# 输出最终结果--简略版
# 简略版
lst3 = sorted(lst2, reverse=True)
print('最终比赛成绩为:')
print(lst3)

# 下面为带编号输出(可用在操作列表学习后)
#lst3 = []
#for i in range(len(lst2)):
#    lst3.append([lst2[i], i])
#lst3.sort(reverse=True)
#print('得分 编号')
#for v in lst3:
#    print('{}   {}'.format(*v))
现场赛计分程序
请输入0号选手的评委得分,以空格分开(q或Q退出):Q
比赛结束!
最终比赛成绩为:
[]

三、操作列表¶

In [60]:
# 遍历整个列表
names = ['小林', '张三', '李四', '小明']
print('选手名单如下:')
for i in range(4):
    print('Hello, {}.'.format(names[i]))
选手名单如下:
Hello, 小林.
Hello, 张三.
Hello, 李四.
Hello, 小明.
In [62]:
# 遍历整个列表
names = ['小林', '张三', '李四', '小明']
print('选手名单如下:')
for  name in names:
    print('Hello, {}.'.format(name))
选手名单如下:
Hello, 小林.
Hello, 张三.
Hello, 李四.
Hello, 小明.
In [63]:
lst1 = [78.5, 77.3, 79.1, 78.0, 77.0]
mx = lst1[0]
for num in lst1:
    if num > mx:
        mx = num
print(mx)
79.1
In [67]:
# 2.使用列表的一部分
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = a[1:9:2]
c = a[ : : ]
d = a[ : :-2]
e = a[-1:5]
print(a, b, c, d, e, sep='\n')
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 7, 5, 3, 1]
[]
In [69]:
# 回文数
print('判断回文数')
s = input('请输入一个整数:')
if s == s[::-1]:
    r = '是'
else:
    r = '不是'
print('{} {} 回文数。'.format(s, r))
判断回文数
请输入一个整数:123123
123123 不是 回文数。
In [70]:
# 拓展阅读: 代码规范与Pythonic
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [78]:
def pd(s):
    '''判断回文数'''
    for i in range(len(s)//2):
        if s[i] != s[-1-i]:
            return False
            break  # 该语句多余,舍去。
    return True
print(pd('134431'))
print(pd('1'))
True
True
In [82]:
print('判断回文数')
s = input('请输入一个整数:')
r = '是' if s == s[::-1] else '不是'
print('{} {} 回文数。'.format(s, r))
判断回文数
请输入一个整数:
 是 回文数。

四、列表应用¶

In [92]:
# 石头剪子布
import random
# 你出
user = int(input('请你出(1.石头;2.剪子;3.布):'))
if user == 1:
    result1 = '石头'
elif user == 2:
    result1 = '剪子'
else:
    result1 = '布'
print('你出:{}!'.format(result1))
# 计算机出
computer = random.randint(1,3)
if computer == 1:
    result2 = '石头'
elif computer == 2:
    result2 = '剪子'
else:
    result2 = '布'
print('计算机出:{}!'.format(result2))
# 判断输赢
if user == computer:
    print('平局。')
elif user == 1 and computer == 2:
    print('你赢了!')
elif user == 1 and computer == 3:
    print('你输了!')
elif user == 2 and computer == 1:
    print('你输了!')
elif user == 2 and computer == 3:
    print('你赢了!')
elif user == 3 and computer == 1:
    print('你赢了!')
elif user == 3 and computer == 2:
    print('你输了!')
请你出(1.石头;2.剪子;3.布):2
你出:剪子!
计算机出:石头!
你输了!
In [94]:
# 优化版石头剪子布
import random
choice = ['', '石头', '剪子', '布']
result = ['你输了!', '你赢了!', '平局。', '你输了!', '你赢了!']
user = int(input('请你出(1.石头;2.剪子;3.布):'))
print('你出:{}!'.format(choice[user]))
computer = random.randint(1, 3)
print('计算出:{}!'.format(choice[computer]))
print(result[user - computer + 2])
请你出(1.石头;2.剪子;3.布):1
你出:石头!
计算出:布!
你输了!

体验活动:完善石头剪子布游戏程序¶

In [2]:
3 参考代码
import random
def game():
    choice = ['', '石头', '剪子', '布']
    result = [ '平局。', '你输了!', '你赢了!']
    user = int(input('请你出(1.石头;2.剪子;3.布):'))
    print('你出:{}!'.format(choice[user]))
    computer = random.randint(1, 3)
    print('计算出:{}!'.format(choice[computer]))
    r = user - computer 
    print(result[r])
    return r

count = [0, 0, 0]  # 结果计数(平输赢)
n = int(input('你要玩几局?'))
while n > 0:
    tmp = game()
    count[tmp] += 1
    print('【本轮】平局:{}; 你输:{}; 你赢{},余下{}局。'.format(count[0],count[1], count[2], n))
    n = n -1
print('游戏结束。')
if count[1] == count[2]:
    print('本轮游戏平局。')
elif count[1] < count[2]:
    print('本轮游戏你赢了!')
else:
    print('本游戏你输了。')
你要玩几局?3
请你出(1.石头;2.剪子;3.布):1
你出:石头!
计算出:布!
你输了!
【本轮】平局:0; 你输:1; 你赢0,余下3局。
请你出(1.石头;2.剪子;3.布):2
你出:剪子!
计算出:石头!
你输了!
【本轮】平局:0; 你输:2; 你赢0,余下2局。
请你出(1.石头;2.剪子;3.布):2
你出:剪子!
计算出:剪子!
平局。
【本轮】平局:1; 你输:2; 你赢0,余下1局。
游戏结束。
本游戏你输了。
In [ ]: