Python3 Cookbook(001)

#將N個元素的元組或序列分解成N個單獨變數list1 = [1, 2, 3, 4, 5, 6]tuple1 = (1, 2, 3, 4, 5, 6)a, b, c, d, e, f = list1print(a, b, c, d, e, f)a, b, c, d, e, f = tuple1print(a, b, c, d, e, f)_, _,_, _, a, b = list1print(a) #獲取aprint(*list1)print(*tuple1)for i in list1: print(i , end =,)for i in abdbbtg: print(i ,end=,)1 2 3 4 5 61 2 3 4 5 61 2 3 4 5 61 2 3 4 5 61,2,3,4,5,6,a,b,d,b,b,t,g,-------------------------------------------------------------------------------#叢任儀長度的可迭代對象中分解元素list1 = [1, 2, 3, 4, 5, 6]a, *b, c = list1print(a)print(*b)print(c)def avg(args): return sum(args )/ len(args)def drop_fist_last(grades): fist, *middle, last = grades print(middle, type(middle)) return avg(middle)print(drop_fist_last(list1))12 3 4 56[2, 3, 4, 5] <class list>3.5record = (Dave, 5979@qq.com, 6666666666, 777777777)name, email, *phone_number = recordprint(name)print(email)print(phone_number)------------------------------------------------------------------------------------*trailing, current = [10, 9, 6, 4, 6, 7,8, 2]print(trailing, type(trailing))print(*trailing)print(current)Dave5979@qq.com[6666666666, 777777777][10, 9, 6, 4, 6, 7, 8] <class list>10 9 6 4 6 7 82------------------------------------------------------------------------------records = [ (foo, 1, 2), (bar, hello), (foo, 3, 4)]def do_foo(x, y): print(foo, x ,y)def do_bar(s): print(bar, s)for tag, *args in records: if tag == foo: do_foo(*args) elif tag == bar: do_bar(*args)foo 1 2bar hellofoo 3 4-----------------------------------------------------------------------------------line = apple:system,BlinkMacSystemFont,Helvetica Neue,PingFang SC,Microsoft YaHei:Sans CJK SC,WenQuanYi Micro Hei,sans:serifuname, *fields, homedir, sh = line.split(:)print(uname)print(homedir)print(sh)print(fields)records = [AVCN, 50, 123.45, (12, 23, 3020)]name, *_, (*_, year) = recordsprint(name)print(year)items = [1, 2, 3, 4, 5, 6]head, *tail = itemsprint(head)print(tail)appleSans CJK SC,WenQuanYi Micro Hei,sansserif[system,BlinkMacSystemFont,Helvetica Neue,PingFang SC,Microsoft YaHei]AVCN30201[2, 3, 4, 5, 6]--------------------------------------------------------------------------if else

推薦閱讀:

如何提高你的收入 | 你應該做的更深還是更廣?
(未完成)2018.04.NO.6(Note)
~廣告設計練習~2017.10.01~10.12份

TAG:Python3x | PythonCookbook書籍 | 練習 |