您的位置:首页 > 理论基础 > 数据结构算法

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

2018-02-01 17:08 676 查看
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/1o75GKZ4import 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)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: