第二周Day2——Python容器

第二周 Day 2 ——Python容器

一、列表

1.容器型数据类型 —— 一个变量可以保存多个数据

通过循环可以完成对列表中每个元素的操作。

列表重复运算

a = [0, 0, 0, 0, 0, 0]
b = [0] * 6
print('a:', a)          # a: [0, 0, 0, 0, 0, 0]
print('b:', b)          # b: [0, 0, 0, 0, 0, 0]
# 字符串也可以重复运算
s = 'hello' * 6         
print('s:', s)          # s: hellohellohellohellohellohello

练习:把一个骰子摇6000次,统计每一面出现的次数

import random
fs = [0] * 6
for _ in range(6000):
    face = random.randint(1, 6)
    # 获取列表元素的索引运算
    fs[face - 1] += 1
for i in range(len(fs)):
    print(f'{i + 1}点出现了{fs[i]}次')

# 1点出现了995次
# 2点出现了998次
# 3点出现了1025次
# 4点出现了1000次
# 5点出现了996次
# 6点出现了986次

软硬件中存在问题和缺陷 -------> bug -------> debug(找出缺陷,解决问题)

2.列表生成式(推导式) —— 创建列表的一种字面量语法
# 1 ~ 100
a = [x for x in range(1, 101)]
print(a)
# 1 ~ 100 的偶数
b = [x for x in range(2, 101, 2)]
print(b)
# 3或5的倍数
c = [x for x in range(1, 101) if x % 3 == 0 or x % 5 == 0]
print(c)
# 1 ~ 10 的数的平方
d = [x * x for x in range(1, 11)]
print(d)

练习:

双色球:6个红色球,1个蓝色球
红色球:1-33选6个(不重复)球
蓝色球:1-16选1个球
实现一个双色球随机选号的程序

n = int(input('机选几注:'))
for _ in range(n):
    red_balls = [x for x in range(1, 34)]
    selected_balls = []
    """
    for _ in range(6):
        index = random.randrange(len(red_balls))
        selected_balls.append(red_balls.pop(index))
    """
    # 通过random模块的sample函数实现无放回抽样
    selected_balls = random.sample(red_balls,6)    # 可以直接代替上面三行代码
    blue_ball = random.randint(1, 16)
    selected_balls.sort()
    selected_balls.append(blue_ball)
    for ball in selected_balls:
        # print('%.2d' % ball, end=' ')
        print(f'{ball:0>2d}', end=' ')          # 2 -> 02   8 -> 08
    print()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ea6RQJBc-1611654954910)(D:\千峰\QQ图片20210126152602.jpg)]

排序:;列表.sort()

默认升序,从下到大

降序:列表.sort(reverse=True)

练习:Josephu环问题
有15个男人和15个女人乘船在海上遇险,为了让一部分人活下来,
不得不将其中15个人扔到海里,有个人想了个办法让大家围成一个圈,
由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,
报到9的人继续扔到海里面,直到将15个人扔到海里。
最后15个女人都幸免于难,15个男人都被扔到了海里。
问这些人最开始是怎么站的,哪些位置是男人,哪些位置是女人。

count = 0
humans = [1] * 30
index = 0
num = 1
while count < 15:
    index %= 30
    if humans[index] and num % 9 == 0:
        count += 1
        humans[index] = 0
        index += 1
        num += 1
    elif humans[index]:
        index += 1
        num += 1
    elif not humans[index]:
        index += 1
for human in humans:
    print('女' if human else '男', end="")

+= 1
elif not humans[index]:
index += 1
for human in humans:
print(‘女’ if human else ‘男’, end="")


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值