Python数据结构的一些技巧、数据结构练习、循环与判断练习题

本文介绍了Python数据结构的使用技巧,如利用sorted函数进行排序,理解其不改变原列表的特性,以及如何使用默认参数实现逆序排列。同时,文章探讨了列表推导式的应用,并展示了如何在循环中获取元素的索引。此外,还提供了数据结构的练习,如词频统计,以及包含循环与判断的实战练习,如模拟摇色子赌大小的游戏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python数据结构的一些技巧

多重循环

sorted函数按照长短、大小、英文字母的顺序给每个列表中的元素进行排序。sorted函数不会改变列表本身顺序,可以理解为先将列表进行复制,再进行顺序的整理,

num_list = [6,2,7,4,1,3,5]
print(sorted(num_list))

在使用默认参数reverse后李彪可以按照逆序整理:

sorted(num_list,reverse=True)
如果同时需要两个列表,使用zip函数
for a,b in zip(num,str):
print(b,'is',a)

推导式:

字典推导式的方式略有不同,主要是因为创建字典必须满足键-值得两个条件才能达成:

d = {i:i+1 for i in range(4)}
g = {i:j for i,j in zip(range(1,6),'abcde')}
g = {i:j.upper() for i,j in zip(range(1,6),'abcde')}


循环列表时获取元素的索引


列表时有序的,使用Python中独有的enumerate来进行索引的获取:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for num,letter in enumerate(letters):
print(letter,'is',num + 1)

Python数据结构练习

为了理解列表的使用方法,通过一个词频统计来练习,需要瓦尔登湖的文本,下载地址http://pan.baidu.com/s/1o75GKZ4

import string

path = 'E:\\Python Code\\Walden.txt'

with open(path,'r',encoding='utf-8') as text:
    words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]
    words_index = set(words)
    counts_dict = {index:words.count(index) for index in words_index}
    
for word in sorted(counts_dict,key = lambda x:counts_dict[x],reverse =True):
    if counts_dict[word]>100:
        print('{}--{} times'.format(word,counts_dict[word]))


python循环与判断练习题

def number_test():
    CN_mobile =[134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705]
    CN_union = [130,131,132,155,156,185,186,145,176,1709]
    CN_telecom = [133,153,180,181,189,177,1700]
    number = input('Enter Your number:')
    number_len = len(number)!=11
    if number_len:
        print('Invalid length,your number should be in 11 digits')
        number_test()
    elif int(number[0:3]) in CN_mobile or int(number[0:4]) in CN_mobile:
        print('Operator:China Mobile')
        print("We're sending verification code via text to your phone:%s",number)
        
    elif int(number[0:3]) in CN_union or int(number[0:4]) in CN_union:
        print('Operator:China Union')
        print("We're sending verification code via text to your phone:%s",number)
        
    elif int(number[0:3]) in CN_telecom or int(number[0:4]) in CN_telecom:
        print('Operator:China Telecom')
        print("We're sending verification code via text to your phone:%s",number)
        
    else:
        print('No such a operator')
        number_test()
number_test()

2、摇色子赌大小


import random
def roll_dice(number=3,points=None):
    print("<<<<<ROLL THE DICE!>>>>>")
    if points == None:
        points = []
    for i in range(1,number+1):
        points.append(random.randrange(1,7))
    return points

def roll_result(total):
    isBig = 11<=total <=18
    isSmall = 3<=total <= 10
    if isBig:
        return 'Big'
    elif isSmall:
        return 'Small'

def roll_start():
    your_money=1000
    while your_money>0:
        print('<<<<< GAME STARTS <<<<<')
        choices = ['Big','Small']    
        your_choices = input('Big or Small:')    
        if your_choices in choices:
            your_bet = int(input('How much you wanna bet?'))
            points = roll_dice()
            total = sum(points)
            youWin = your_choices == roll_result(total)
            if youWin:
                print('The points are',points,'you Win!')
                your_money = your_money + your_bet
                print('You gained {},you have {} now'.format(your_bet,your_money))            
            else:
                print('The points are',points,'you Lose!')
                your_money = your_money - your_bet
                print('You lost {},you have {} now'.format(your_bet,your_money))      
        else:
            print('Invalid Words!')
    else:
         print('Game Over')


roll_start()
1.
def creat_txt():
    path = '/Users/zwb/Desktop/abc/'
    for i in range(1,11):
        with open(path +str(i)+'.txt','w') as text:
            text.write(str(i))
            text.close()

creat_txt()

2.
def invest(amount,time,rate=0.05):
    print("principal amount:%d"%amount)
    for i in range(1,time+1):
        amount =amount + amount * rate
        print("year {} :$ {}".format(i,amount))

invest(100,8)
invest(2000,5,.025)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值