2020-02-09python學(xué)習(xí)

python基本數(shù)據(jù)結(jié)構(gòu)(八)

    1. 逐個(gè)打印元素
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] 抱歉不報(bào)后
for day in weekdays:
    print(day) # 返回list中的每一個(gè)元素
#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(): # 調(diào)用函數(shù) + ()硬霍,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")

# 每次詢(xún)問(wèn)记某,用戶(hù)決定何時(shí)退出
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——查詢(xún)build-in function
# for else ,如果遇到 break打印糠馆,沒(méi)有遇到不打印纪隙。
for i in range(10):
    print(i)
    if i==15:
        break
else:
    print("no break")
---
list(range(1,100)) # range(a,b),從a開(kāi)始,到b-1結(jié)束生成數(shù)列

# 猜數(shù)
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="")# 指定結(jié)尾符號(hào)
    print("")
for i in range(4):
    for j in range(i+1):
        print("x",sep='',end="")# 指定結(jié)尾符號(hào)
    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)] #總結(jié),墻邊的操作可以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')

# 少輸入?yún)?shù)的默認(rèn)處理
def nonbuggy(arg,result=None):
    if result is None:
        result=[]
    print(id(result))
    result.append(arg)
    print(result)

nonbuggy('a')
nonbuggy('b')

# *args 輸入多個(gè)參數(shù),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) # 顯示說(shuō)明信息

# lambda function
double= lambda x: x*3
double(3) # similar f=@(x) x*3 in matlab
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末怜姿,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子疼燥,更是在濱河造成了極大的恐慌沧卢,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,123評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件醉者,死亡現(xiàn)場(chǎng)離奇詭異但狭,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)撬即,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門(mén)立磁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人搞莺,你說(shuō)我怎么就攤上這事息罗。” “怎么了才沧?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,723評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵迈喉,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我温圆,道長(zhǎng)挨摸,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,357評(píng)論 1 283
  • 正文 為了忘掉前任岁歉,我火速辦了婚禮得运,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘锅移。我一直安慰自己熔掺,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,412評(píng)論 5 384
  • 文/花漫 我一把揭開(kāi)白布非剃。 她就那樣靜靜地躺著置逻,像睡著了一般。 火紅的嫁衣襯著肌膚如雪备绽。 梳的紋絲不亂的頭發(fā)上券坞,一...
    開(kāi)封第一講書(shū)人閱讀 49,760評(píng)論 1 289
  • 那天,我揣著相機(jī)與錄音肺素,去河邊找鬼恨锚。 笑死,一個(gè)胖子當(dāng)著我的面吹牛倍靡,可吹牛的內(nèi)容都是我干的猴伶。 我是一名探鬼主播,決...
    沈念sama閱讀 38,904評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼塌西,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼蜗顽!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起雨让,我...
    開(kāi)封第一講書(shū)人閱讀 37,672評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤雇盖,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后栖忠,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體崔挖,經(jīng)...
    沈念sama閱讀 44,118評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,456評(píng)論 2 325
  • 正文 我和宋清朗相戀三年庵寞,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了狸相。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,599評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡捐川,死狀恐怖脓鹃,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情古沥,我是刑警寧澤瘸右,帶...
    沈念sama閱讀 34,264評(píng)論 4 328
  • 正文 年R本政府宣布娇跟,位于F島的核電站,受9級(jí)特大地震影響太颤,放射性物質(zhì)發(fā)生泄漏苞俘。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,857評(píng)論 3 312
  • 文/蒙蒙 一龄章、第九天 我趴在偏房一處隱蔽的房頂上張望吃谣。 院中可真熱鬧,春花似錦做裙、人聲如沸岗憋。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,731評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)仔戈。三九已至,卻和暖如春惋鸥,著一層夾襖步出監(jiān)牢的瞬間杂穷,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,956評(píng)論 1 264
  • 我被黑心中介騙來(lái)泰國(guó)打工卦绣, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留耐量,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,286評(píng)論 2 360
  • 正文 我出身青樓滤港,卻偏偏與公主長(zhǎng)得像廊蜒,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子溅漾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,465評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容

  • 這是16年5月份編輯的一份比較雜亂適合自己觀看的學(xué)習(xí)記錄文檔山叮,今天18年5月份再次想寫(xiě)文章,發(fā)現(xiàn)簡(jiǎn)書(shū)還為我保存起的...
    Jenaral閱讀 2,737評(píng)論 2 9
  • 個(gè)人筆記添履,方便自己查閱使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik閱讀 67,682評(píng)論 0 5
  • Sort a linked list using insertion sort. 一刷題解:沒(méi)有很好的辦法屁倔,只能每...
    Jeanz閱讀 244評(píng)論 0 0
  • 最近一段時(shí)間,幣市大跌暮胧。 有新聞報(bào)道說(shuō)比特幣從巔峰的18000美金跌到了8000美金锐借,腰斬! 縱然以最高價(jià)來(lái)對(duì)比現(xiàn)...
    Amirazhou閱讀 116評(píng)論 0 0
  • 今天媽媽下班回來(lái)往衷,讓我讀預(yù)習(xí)的課文钞翔。我沒(méi)讀好,媽媽非常生氣席舍,因?yàn)槲覜](méi)有聽(tīng)媽媽的話(huà)布轿,今天去預(yù)習(xí)課文。本來(lái)舅媽說(shuō)帶我和...
    李艾娟閱讀 160評(píng)論 0 0