python基本数据结构(八)
weekdays=['Monday','Tuesday','Wednesday','Thursday','Friday']
print(weekdays)
i=0
while i< len(weekdays):
print(weekdays[i])
i+=1
# range method
list(range(len(weekdays))) # 返回sequence,用于loop
# [0, 1, 2, 3, 4] 抱歉不报后
for day in weekdays:
print(day) # 返回list中的每一个元素
#type(enumerate(weekdays))
for key,day in enumerate(weekdays):
print(str(key)+" "+day) # enumerare return a tuple,including index and value
my_list=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
for c,value in enumerate(my_list,1): # 指定index的起始位置
print(c,value)
pizza={
"size":"medium",
"type":"pepperoni",
"crust":"Thick",
"qty":1,
"deliver":True
}
for k,v in pizza.items(): # 调用函数 + (),items返回key&value pair
print("key is {},value is {}".format(k,v))
# range returns a sequence
num_list=[i for i in range(0,10)] # list comprehensions
num_list
num_list=list(range(1,10,2))
num_list # return a odd list
num_list=[i for i in range(0,10) if i%2==1]
num_list # 添加filter的list comprehensions
num_list=[]
num_list=[i**2 for i in range(500) if i%3==2]
#num_list
#type(num_list)
gen=(i*i for i in range(500) if i%3==2)
gen
type(gen) # data type generator
# print generator number
for num in gen:
print(num) # print generator
# random function
import random
num_list=random.sample(range(10),10) # pick k unique elements from population
target=5
print("list=",num_list)
print("target=",target)
l1=[x for x in num_list if x< target]
l2=[x for x in num_list if x>=target]
#list comprehensions default return a generator
print("l1 is ",l1)
print("l2 is {}".format(l2))
l2=[x for x in num_list if x not in l1]
print("l2:",l2) # not in syntax
print("num_list:",num_list)
rows=range(1,4)
cols=range(1,3)
cells=[]
for row in rows:
for col in cols:
cells.append([row,col]) # appedn only takes exactly one argument
cells # nested method
# Above loop can be writtern in the
cells=[[r,c] for r in rows for c in cols]
cells # list comprehension method
builder_list=[]
string_build=""
for data in container:
builder_list.append(str(data))
"".join(builder_list)
# antother way is to use a list comprehension
"".join([str(data) for data in container])
# or use map function
"".join(map(str,container))
Python code structures
possibility_to_rain=0.7
if possibility_to_rain> 0.8:
print("Do take your umberalla with you.")
elif possibility_to_rain>0.3:
print("Take your umberalla just in case. hhhaha")
else:
print("Enjoy the sunshine!")
card_type="debit"
account_type="checking"
if card_type=="debit":
if account_type=="checking":
print("Checkings selected.")
else:
print("Saving selected.")
else:
print("Credit card.")
x=int(input("Please enter an integer:\n"))
if x < 0:
x=0
print("Negative changed to zero")
elif x==0:
print("Zero")
elif x==1:
print("Single")
else:
print("More")
switch case
class SMTP:
def lookupMethod(self,command):
return getattr(self,'do_'+ command.upper(),None)
def do_HELO(self,rest):
return 'Howdy '+rest
def do_QUIT(self,rest):
return 'Bye'
SMTP().lookupMethod('HELO')('foo.bar.com') #=>'howdy foo.bar.com'
SMTP().lookupMethod('QUIT')('') # =>'Bye'
# while loop
cnt=1
while cnt<=5:
print('cnt=%d' % cnt)
cnt+=1
print("finish")
# 每次询问,用户决定何时退出
cnt=1
while True:
print('cnt=%d' % cnt)
ch=input('Do you want to continue? [y|n]:')
if ch=='y':
cnt+=1
else:
break
# for loop
# ?range——查询build-in function
# for else ,如果遇到 break打印,没有遇到不打印。
for i in range(10):
print(i)
if i==15:
break
else:
print("no break")
---
list(range(1,100)) # range(a,b),从a开始,到b-1结束生成数列
# 猜数
from random import randint
mystery=randint(1,100)
times=3
print("I've thought a number from 1 to 100. You have %s times to guest it out" % times)
def guess_number(times):
for i in range(0,times):
user_input=int(input("Please enter a number:\n>>>"))
if user_input==mystery:
print("Great, you are right, the number is %s." % mystery)
break
elif user_input>mystery:
print("Your input is too big.")
print("You have %s times left. Good luck!" %(times-i))
else:
print("Your input is too small.")
print("You have %s times left. Good luck!" % (times-i))
print("")
print("Game is over...")
guess_number(5)
---
# nested loop
for i in range(4):
for j in range(10):
print("x",sep='',end="")# 指定结尾符号
print("")
for i in range(4):
for j in range(i+1):
print("x",sep='',end="")# 指定结尾符号
print("") # 阶梯型
for i in range(5):
for j in range(5+1):
if i+j>4:
print("x",end='')
else:
print('T',end='')
print("") # 指定换行
# list comprehensions
[[[0] for x in range(5)] for x in range(5)] # 初始化5*5list
[[0]*5 for x in range(5)] #总结,墙边的操作可以list comprehension
---
# dictionary comprehension
# Count number of each base in the dna sequence
dna='ACCGAATTAGT'
dna_cnt={b : dna.count(b) for b in set(dna)}
dna_cnt # set() constructure
# {'A': 4, 'C': 2, 'T': 3, 'G': 2}
# function
# An empty function that does nothing
def do_nothing():
pass
type(do_nothing)
# An fucntion without parameters and returns values
def greeting():
print("Hello Pyhton")
# Call the function
a=greeting()
# positional arguments
# A function with 3 parameters
def menu(wine,entree,dessert):
return {'wine':wine,'entree':entree,'dessert':dessert}
# Get a menu
menu('chardonnay','chicken','cake')
# To avoid positional argument confusion. you can specify arguments by the names of their corresponding parameters. even in a different order from their definition in the function.
menu(entree='beef',dessert='bagel',wine='bordeaux') # keyword argument
# You can even mix positional and keyword argument
# Note:You have to provide all positional argument before feed any keyword argumen
---
# default dessert is pudding
def menu(wine,entree,dessert='pudding'):
return {'wine':wine,'entree':entree,'dessert':dessert}
# call menu without providing dessert
menu('chardonnay','chicken')
# default parameter 必须放在最后
# Default value will be overwritten if caller provide a value
menu('chardonnay','chicken','doughnut')
# 少输入参数的默认处理
def nonbuggy(arg,result=None):
if result is None:
result=[]
print(id(result))
result.append(arg)
print(result)
nonbuggy('a')
nonbuggy('b')
# *args 输入多个参数,similat to varargin in matlab.
def print_args(*args):
print('Positional args:',args)
#If your function has require positional arguments as well.write all require arguments before you use *. which will gather all arguments until the very last one.
def print_args_with_require(req1,req2,*args):
print('require arg 1:',req1)
print('require arg 1:',req2)
print('other arguments:',args)
---
def print_kwargs(**kwargs):
print('keyword args:',kwargs)
print_kwargs(first=1,second=1)
# keyword args: {'first': 1, 'second': 1}
def print_all_args(req1,*args,**kwargs):
print('require arg1:',req1)
print('Positional args:',args)
print('keyword args:',kwargs)
print_all_args(1,2,3,s='hello')
#require arg1: 1
#Positional args: (2, 3)
#keyword args: {'s': 'hello'}
# Like we talked eariler. We can
# attach documentation to a
# function definition by including a # string at the beginning of the
# function body. This can be super
# helpful when you are working
# with others or when you're using
# IDE.
def print_if_true(thing,check):
'''
Print the first argument if the second argument is true.
The operation is:
1. check whther the second argument is true
2. If it is, print the first argument.
'''
if check:
print(thing)
# use help to get the docstring of a function
help(print_if_true) # 显示说明信息
# lambda function
double= lambda x: x*3
double(3) # similar f=@(x) x*3 in matlab
网友评论