python笔记

  1. #空白形式  
  2. i = 1 + \  
  3.     2                #反斜线代表一个语句在下一行续写  
  4. # print (i)  
  5.   
  6. #模块  
  7. import re  
  8. my_regex = re.compile("[0-9]+",re.I)  
  9.   
  10. # print (my_regex)  
  11.   
  12. import re as regex     #别名  
  13.   
  14. my_regex = regex.compile("[0-9]+",regex.I)  
  15.   
  16. # print(my_regex)  
  17.   
  18. from collections import defaultdict, Counter   #使用模块中的特定值,显示导入,直接使用,不必提前获取权限  
  19. lookup = defaultdict(int)  
  20. my_counter = Counter()  
  21.   
  22. match = 10         #如果是破坏者,可以将模块的全部内容导入命名空间,这也许会不加提示地覆盖原先定义的变量  
  23. from re import *  #re有一个match函数  
  24. # print(match)       #<function match at 0x0000000002985D08>  
  25.   
  26. #算法  
  27. a = 5 / 2      #结果为float  
  28. a = 5 // 2     #整除  
  29. # print (a)  
  30.   
  31. #函数  
  32. def double(x):  
  33.     return x*2  
  34.   
  35. # print (double(3))  
  36.   
  37. def apply_to_one(f):  
  38.     return f(1)  
  39. my_double = double     #指向之前的函数  
  40. x = apply_to_one(my_double)    #python函数是第一类函数,第一类函数意味着可以将他们赋给其他变量,也可以像其他参数一样传递给函数  
  41.   
  42. # print(x)    #等于2  
  43.   
  44. y = apply_to_one(lambda x:x+4)   #也很容易生成简短的匿名函数,或者lambda  lambda 是为了减少单行函数的定义而存在的。  
  45.   
  46. # print(y)    #等于5  
  47.   
  48. another_double = lambda x:2*x     #可以将lambda赋给变量,不建议这么做  
  49. # print (another_double(2))  
  50. def another_double(x): return 2*x    #建议使用def  
  51. # print(another_double(2))  
  52.   
  53. def my_print(message = "my default message"):      #默认参数可以赋值给函数参数,当你需要默认值以外的值时需要具体说明  
  54.     print(message)  
  55. # my_print("hello")   #输出hello  
  56. # my_print()          #输出my default message  
  57.   
  58. def subtract(a = 0, b = 0):       #有时候通过名字指定参数会有用  
  59.     return a - b  
  60. # print(subtract(10, 5))    #打印5  
  61. # print(subtract(0, 5))     #打印-5  
  62. # print(subtract(b = 5))    #打印-5  
  63.   
  64. #字符串  
  65. single_quoted_string = 'data science'  
  66. double_quoted_string = "data science"    #两个等价  
  67.   
  68. tab_string = "\t"   #表示tab字符  
  69. # print (len(tab_string))   # 1  
  70.   
  71. not_tab_string = r"\t"  #表示字符'\'和't'   使用r""生成一个原始的字符串  
  72. # print (len(not_tab_string))   # 2  
  73.   
  74. multi_line_string = """this is the first line. 
  75. and this is the second line 
  76. and this is the third line"""      #通过三重[两重]引号生成多行的字符串  
  77. # print(multi_line_string)  
  78.   
  79. #异常  
  80. try:  
  81.     print(0/0)  
  82. except ZeroDivisionError:  
  83.     print("cannot divide by zero")  
  84.   
  85. #集合  
  86. integer_list = [123]  
  87. heterogeneous_list = ["string"0.1True]  
  88. list_of_lists = [integer_list, heterogeneous_list, []]  
  89. # print(len(integer_list))  
  90. # print(sum(integer_list))           #列表是一个有序集合,和其他语言中数组概念类似,但增加了函数功能  
  91.   
  92. x = range(10)       #是列表[0, 1, 2, ..., 9]  
  93. zreo = x[0]               # 0  
  94. one = x[1]                # 1  
  95. nine = x[-1]              # 9 ,最后一个元素的python惯用法  
  96. eight = x[-2]             # 8 ,倒数第二个元素的python惯用法  
  97. # x[0] = -1                 # 'range' object does not support item assignment  
  98. # print(x)  
  99.   
  100. first_three = x[:3]    #[0,1,2]  
  101. three_to_end = x[3:]   #[3,4,...,9]  
  102. one_to_four = x[1:5]   #[1,2,3,4]  
  103. last_three = x[-3:]    #[7,8,9]  
  104. without_first_and_last = x[1:-1]  #[1,2,3,...,8]  
  105. copy_of_x = x[:]       #[0,1,2,3,...,9]  
  106. # print(copy_of_x)  
  107.   
  108. # print(1 in [1,2,3])    #True      python可以通过操作符in确认列表成员  
  109. # print(0 in [1,2,3])    #False     确认每次回遍历列表元素,除非列表很小,否则不应该进行确认,除非不在乎需要花费多长时间  
  110.   
  111. x = [1,2,3]  
  112. x.extend([5,6,7])    #串联列表  
  113. # print(x)  
  114. y = x + [4,5,6]  
  115. # print(y)  
  116.   
  117. x.append(0)    #一次在原列表上只增加一项  
  118. # print(x)  
  119. x,y = [1,3]    #如果知道列表中元素的个数,可以方便地从中提取值,现在x是1,y是3,如果等式两端元素个数不同,会报出提示valueError  
  120.   
  121. _,y = [1,3]    #如果希望忽略某些值,常见的选择是使用下划线  
  122. # print(y)     #现在y == 3 不用关心第一个元素是什么  
  123.   
  124. #元组  
  125. my_list = [1,2]       #元组是列表的亲表哥。你对列表做的很多操作都可以对元组做,但不包括修改。元组通过圆括号(或者什么都不加)而不是方括号来给出具体的描述  
  126. my_tuple = (1,2)  
  127. other_tuple = 3,4  
  128. my_list[1] = 3  
  129. # print(my_list)     #my_list现在是[1,3]  
  130.   
  131. try:  
  132.     my_tuple[1] = 3  
  133. except TypeError:  
  134.     print("cannot modify a tuple")  
  135.   
  136. def sum_and_product(x,y):       #元组是通过函数返回多重值的便捷方法  
  137.     return (x+y), (x*y)  
  138. sp = sum_and_product(2,3)  
  139. s,p = sum_and_product(5,10)  
  140. # print(p)  
  141.   
  142. x,y = 1,2  
  143. x,y = y,x      #元组和列表都可以进行多重赋值,python风格的互换变量  
  144. # print(x,y)  
  145.   
  146. #字典  
  147. #python中另一种基本的数据结构是字典,它将值与键联系起来,让我们可以通过键快速找到对应的值  
  148. empty_dict = {}              #python风格  
  149. empty_dict2 = dict()         #更少的python风格  
  150. grades = {"Joel":80,"Tim":95}        #字典  
  151. joels_grade = grades["Joel"]   # 80  
  152. # print(joels_grade)  
  153.   
  154. try:  
  155.     kates_grades = grades["Kate"]      #如果要找的键不在字典中,会得到KeyError报错  
  156. except KeyError:  
  157.     print("no grade for kate!")  
  158.   
  159. joel_has_grade = "Joel" in grades      #True  
  160. kates_has_grade = "Kate" in grades     #False  
  161. # print(joel_has_grade, kates_has_grade)  
  162.   
  163. tweet = {                     #常常使用字典作为代表结构数据的简单方式  
  164.     "user":"joelgrus",  
  165.     "text":"Data Science is Awesome",  
  166.     "retweet_count":100,  
  167.     "hashtags":["#data","#science","#datascience","#awesome","#yolo"]  
  168. }  
  169.   
  170. tweet_key = tweet.keys()   #键的列表            除了查找特定的值,还可以查找所有值  
  171. tweet_values = tweet.values()  #值得列表  
  172. tweet_items = tweet.items()  #(键,值)元组的列表  
  173. # print(tweet_items)  
  174.   
  175. print("user"in tweet_key)   #True 使用慢速的列表  
  176. print("user"in tweet)     #更符合python惯用法,使用快速的字典  
  177. print("joelgrus"in tweet_values)   #True  
  178.   
  179. #defaultdict  
  180. #字典的键不可改变,尤其是不能将列表作为键。如果需要一个多维的键,应该使用元组或设法把键转换成字符串  
  181. document = [] #这是很多单词  
  182. word_counts = {}   #这是一个字典  
  183. for word in document:     #将列表中的单词进行计数  
  184.     if word in word_counts:  
  185.         word_counts[word] += 1   #有词就计数加一  
  186.     else:  
  187.         word_counts[word] = 1    #没词就把词增加到字典中  
  188.   
  189. word_counts = {}  
  190. for word in document:     #当查找缺失值碰到异常报出时,可以遵循“与其瞻前顾后,不如果断行动”的原则,果断处理异常  
  191.     try:  
  192.         word_counts[word] += 1  
  193.     except KeyError:  
  194.         word_counts[word] = 1  
  195.   
  196. word_counts = {}  
  197. for word in document:   #用get方法处理缺失值的方法比较优雅  
  198.     previous_count = word_counts.get(word,0)  
  199.     word_counts[word] = previous_count + 1  
  200.   
  201. #以上三种方法都略显笨拙,这是defaultdict的意义所在。一个defaultdict相当于一个标准的字典,除了当你查找一个没有包含在内的键时,  
  202. # 它用一个你提供的零参数函数建立一个新的键,并为它的值增加1.  
  203. from collections import defaultdict  
  204. word_counts = defaultdict(int)  #int()生成0  
  205. for word in document:  
  206.     word_counts[word] += 1  
  207.   
  208. #这对列表、字典或者自己的函数都有用  
  209. dd_list = defaultdict(list)    #list()生成一个空列表  
  210. dd_list[2].append(1)           #现在dd_list包含{2:[1]}  
  211.   
  212. dd_dict = defaultdict(dict)    #dict()产生一个新字典  
  213. dd_dict["Joel"]["City"] = "Seattle"  #{"Joel":{"City":Seattle}}  
  214. # print(dd_dict)  
  215.   
  216. dd_pair = defaultdict(lambda :[0,0])  
  217. dd_pair[2][1] = 1              #现在dd_pair包含{2:[0,1]}  
  218. # print(dd_pair)               #当我们用字典“收集”某些键对应的结果,并且不希望每次查找某键是否存在都遍历一遍的时候,defaultdict非常有用  
  219.   
  220. #counter  
  221. #一个计数器将一个序列的值转化成一个类似于整形的标准字典,即defaultdict(int),的键到计数的对象映射。我们主要用它来生成直方图  
  222. from collections import Counter  
  223. c = Counter([0,1,2,0])           #C是(基本的){0:2,1:1,2:1}  
  224. # print(c)  
  225. word_counts = Counter(document)   #这给我们提供了一个用来解决单词计数问题的很简便的方法  
  226.   
  227. for word,count in word_counts.most_common(10):    #一个counter实例带有的most_common方法的例子,打印最常见的10个单词和它们的计数  
  228.     print(word, count)  
  229.   
  230. #集合  
  231. # 另一种数据结构是集合(set),它表示为一组不同的元素:  
  232. s = set()  
  233. s.add(1)    #s = {1}  
  234. s.add(2)    #s = {1,2}  
  235. s.add(2)    #s = {1,2}  因为set中元素是不同的  
  236. x = len(s)  # x = 2  
  237. y = 2 in s  # y = True  
  238. z = 3 in s  #z = False  
  239. # print(z)  
  240.   
  241. #使用集合的原因:1、集合上有一种非常快速的操作:in。如果我们有大量的项目,希望对它的成分进行测试,那么使用集合鄙视用列表合适得多:  
  242. hundreds_of_other_words = []      #这是很多word  
  243. stopwords_list = ["a","an","at"]+hundreds_of_other_words+["yet","you"]  
  244. # print ("zip" in stopwords_list)    #False,但需要检查每个元素  
  245. stopwords_set = set(stopwords_list)  
  246. "zip" in stopwords_set    #非常快速地检查  
  247. #2、便于在一个汇总中寻找其中离散的项目:  
  248. item_list = [1,2,3,1,2,3]  
  249. num_items = len(item_list)    # 6  
  250. item_set = set(item_list)     #{1,2,3}   去重  
  251. num_distinct_items = len(item_set)   # 3  
  252. distinct_item_list = list(item_set)  #[1,2,3]  
  253. #我们使用set的频率远低于dict和list  
  254.   
  255. #控制流  
  256. if 1>2:  
  257.     message = "if only 1 were greater than two..."  
  258. elif 1>3:  
  259.     message = "elif stands for 'else if'"  
  260. else:  
  261.     message = "when all else fails use else(if yu want to)"  
  262. # print(message)  
  263.   
  264. parity = "even" if x % 2 == 0 else "odd"    #可以在一行语句中使用if-then-else  
  265. # print(parity)  
  266.   
  267. x = 0  
  268. while x < 10:  
  269.     # print(x,"is less than 10")  
  270.     x += 1  
  271.   
  272. # for x in range(10):  
  273.     # print(x,"is less than 10")  
  274.   
  275. for x in range(10):  
  276.     if x == 3:  
  277.         continue   #直接进入下次迭代  
  278.     if x == 5:  
  279.         break      #完全退出循环  
  280.     # print(x)      # 打印0,1,2,4  
  281.   
  282. #真和假  
  283. #python的布尔数除了首字母大写之外,其他用法和大多数别的语言类似  
  284.   
  285. one_is_less_than_two = 1<2  
  286. # print(one_is_less_than_two)    #True  
  287.   
  288. true_equals_false = True == False   #False  
  289. # print(true_equals_false)  
  290.   
  291. x = None            #python使用None来表示一个不存在的值,它类似于别的语言中的null  
  292. # print(x == None)   # 打印True   但不是python的惯用法  
  293. # print (x is None)     #打印True   符合python的惯用法  
  294.   
  295. #Python可以使用任何可被认为是布尔数的值。下面这些都是“假”(Falsy)  
  296. False,None,[],{},"",set(),0,0.0  
  297.   
  298. def some_function_that_returns_a_string():  
  299.     return "a"  
  300. s = some_function_that_returns_a_string()  
  301. if s:  
  302.     first_char = s[0]  
  303. else:  
  304.     first_char = ""  
  305.   
  306. #另一种简单的做法:  
  307. first_char = s and s[0]   #第一个值为"真"时,and运算符返回它的第二个值,否则返回第一个值  
  308. # print(first_char)  
  309.   
  310. safe_x = x or 0     #如果x取值可能是一个数可能是None,返回结果必然是一个数字  
  311. # print(safe_x)  
  312.   
  313. list = [1,2,3,0]       #all函数的取值是一个列表,当列表的每个元素都为真时返回True,any函数取值的列表中至少有一个元素为真时,返回True  
  314. # print(all(list))     #False  
  315. # print(any(list))       #True  
  316.   
  317. #排序  
  318. x = [4,1,2,3]  
  319. # y = sorted(x)   #x不改变  
  320. # print(x,y)  
  321. # x.sort()        #x改变  
  322. # print(x,y)  
  323.   
  324. #默认情况下,sort和sorted给予元素之间的朴素比较从最小值到最大值对列表进行排序  
  325. # 如果想从最大到最小排序,可以指定参数reverse=True。  
  326. # 除了比较元素本身还可以通过指定键来对函数的结果进行比较  
  327. x = sorted([-4,1,-2,3], key = abs, reverse = True)   #通过绝对值对列表元素从最大到最小排序  
  328. # print(x)    #[-4, 3, -2, 1]  
  329.   
  330.   
  331.   
  332. wc = sorted(word_counts.items(),             #从最高数到最低数排序单词和计数  
  333.             # key = lambda (word,count):count,      #会报错   拓扑参数在python3中不被支持  
  334.             reverse = True)  
  335.   
  336. #列表解析  
  337. #我们有时可能会想把一个列表转换为另一个列表,例如只保留其中一些元素,或更改其中一些元素,  
  338. # 或者同时做这两种变动。可以执行这种操作的python技巧叫做列表解析(list comprehension)  
  339. even_numbers = [x for x in range(5if x%2 == 0]  #[0,2,4]  
  340. squares = [x*x for x in range(5)]     #[0,1,4,9.16]  
  341. even_squares = [x*x for x in even_numbers]    #[0,4,16]  
  342. # print(even_squares)  
  343.   
  344.   
  345. #类似地,可以把列表转换为字典和集合  
  346. square_dict = {x:x*x for x in range(5)}    #0: 0, 1: 1, 2: 4, 3: 9, 4: 16}  
  347. squre_set = {x*x for x in [-1,1]}          #{1}  
  348. # print(squre_set)  
  349.   
  350. #如果你不需要来自原列表中的值,常规的方式是使用下划线作为变量  
  351. zeroes = [0 for _ in even_numbers]     #和even_number有相同的长度[0, 0, 0]  
  352. # print(zeroes)  
  353.   
  354. pairs = [(x,y)                   #列表解析可以包括多个for语句  
  355.          for x in range(10)  
  356.          for y in range(10)]    #100对数据  
  357. # print(pairs)  
  358.   
  359. #后面的for语句可以使用前面的for语句结果  
  360. increasing_pairs = [(x,y)                   #只考虑 x<y的对  
  361.                     for x in range(10)      #range(lo,hi)与之相等  
  362.                     for y in range(x+1,10)] #[lo,lo+1,...,hi-1]  
  363. # print(increasing_pairs)  
  364.   
  365. #生成器和迭代器  
  366. #生成器(generator)是一种可以对其产生迭代(对我们来说,通常使用for语句)的程序,但是它的值只按需延迟(lazily)产生  
  367.   
  368. #创建生成器的一种方法时使用函数和yield运算符  
  369. def lazy_range(n):  
  370.     """a lazy version of range"""  
  371.     i = 0  
  372.     while i < n:  
  373.         yield i            #yield是一个关键词,类似return, 不同之处在于,yield返回的是一个生成器  
  374.         i += i  
  375. #         print(i)  
  376. # for i in lazy_range(10):  
  377. #     i += 1  
  378. #     print(i)  
  379.   
  380. #python确实有一个和lazy_range一样的函数,叫做xrange,并且在python3中,range函数本身就是延迟的,这意味着,你甚至可以创建一个无限的序列  
  381. def natural_numbers():  
  382.     """return 1,2,3..."""  
  383.     n = 1  
  384.     while True:          #尽管在没有使用某种break逻辑语句时,不应该做这种迭代  
  385.         yield n  
  386.         n+=1  
  387.         print(n)  
  388.   
  389. #延迟的缺点是,你只能通过生成器迭代一次。如果需要多次迭代某个对象,你就需要每次都重新创建一个生成器,或者使用列表  
  390.   
  391. #第二种创建生成器的方法是使用包含在圆括号中的for语句解析:  
  392. lazy_evens_below_20 = (i for i in lazy_range(20if i%2 == 0)  
  393. lazy_evens_below_20.__next__()  
  394. # print(lazy_evens_below_20)   #<generator object <genexpr> at 0x0000000002A4E888>  
  395.   
  396. def h(n):  
  397.   while n>0:  
  398.     m = (yield n)  
  399.     print ("m is "+str(m))  
  400.     n-=1  
  401.     print ("n is "+str(n))  
  402. p= h(5)  
  403. p.__next__()  
  404. p.send("test")  
  405. p.__next__()  
  406.   
  407. #随机性  
  408. import random  
  409. four_uniform_randoms = [random.random() for _ in range(4)]  #random.random()生成在0-1之间均匀分布的随机数,是最常见的随机函数  
  410. # print(four_uniform_randoms)                                #[0.8409394478222172, 0.8725989680572983, 0.43909368270992066, 0.9883409909539946]  
  411.   
  412. #random模块实际上生成的是基于一种内部状态的确定性的伪随机数。如果你想得到可复生的结果,可以用random.seed生成随机数种子:  
  413. random.seed(10)        #设置随机数种子为10  
  414. print(random.random())  #0.5714025946899135  
  415. random.seed(10)   #重设随机数种子为10  
  416. print(random.random())   #再次得到0.5714025946899135  
  417.   
  418. #有时候我们用random.randrange生成随机数,它会取1到2个参数,并从对应的range()函数随机选择一个元素返回:  
  419. print(random.randrange(10))   #从range(10) = [0,1,...,9]中随机选取  
  420. print(random.randrange(3,6))   #range(3,6)= [3,4,5]中随机选取  
  421.   
  422. #random.shuffle可随机地重排列表中的元素:  
  423. up_to_ten = [4,1,3,5,7,8]  
  424. random.shuffle(up_to_ten)    #  [8, 3, 5, 1, 4, 7]   shuffle不支持range重排列  
  425. print(up_to_ten)  
  426.   
  427. my_best_friend = random.choice(["Alice","Bob","Charlie"])  #从列表中随机取一个元素  
  428. print(my_best_friend)  
  429.   
  430. lottery_numbers = range(60)  
  431. winning_numbers = random.sample(lottery_numbers, 6)    #[41, 51, 10, 2, 33, 31] 不重复地随机选择一个元素的样本,可以使用random.sample  
  432. print(winning_numbers)  
  433.   
  434. four_with_replacement = [random.choice(range(10))  #[5, 1, 3, 5] 选择一个允许重复的元素样本,只需多次调用random.choice即可  
  435.                          for _ in range(4)]  
  436. print(four_with_replacement)  
  437.   
  438. #正则表达式  
  439. import re  
  440. print(all([                      #所有这些语句都为True,因为  
  441.     not re.match("a","cat"),    #* 'cat'不以'a'开头  
  442.     re.search("a","cat"),       #* 'cat'里有一个字符'a'  
  443.     not re.search("c","dog"),   #*'dog'里没有字符'c'  
  444.     3 == len(re.split("[ab]","carbs")),     #*分割掉a,b,剩余长度为3  
  445.     "R-D-" == re.sub("[0-9]","-","R2D2")   #用虚线进行位的替换  
  446. ]))  
  447.   
  448. #面向对象编程  
  449. class Set:  
  450.   
  451.     #这些是成员函数  
  452.     #每个函数都取第一个参数"self"(另一种惯例)  
  453.     #它表示所用到的特别的集合对象  
  454.   
  455.     def __init__(self, values = None):  
  456.         """this is the constructor. 
  457.         It gets called when you create a new set. 
  458.         you would use it like 
  459.         s1 = Set()     #空集合 
  460.         s2 = Set([1,2,2,3])   #用值初始化"""  
  461.         self.dict = {}  #Set的每一个实例都有自己的dict属性  
  462.                         #我们会用这个属性来追踪成员关系  
  463.         if values is not None:  
  464.             for value in values:  
  465.                 self.add(value)  
  466.   
  467.     def __repr__(self):  
  468.         """this is the string representation of a Set object 
  469.         if you type it at the Python prompt or pass it to str()"""  
  470.         return ("Set:",str(self.dict.keys()))  
  471.   
  472.     #通过成为self.dict中对应值为True的键,来表示成员关系  
  473.     def add(self, value):  
  474.         self.dict[value] = True  
  475.   
  476.     #如果它在字典中是一个键,那么在集合中就是一个值  
  477.     def contains(self, value):  
  478.         return value in self.dict  
  479.   
  480.     def remove(self, value):  
  481.         del self.dict[value]  
  482.   
  483. s = Set([1,2,3])  
  484. s.add(4)  
  485. print(s.contains(4))    #True  
  486. s.remove(3)  
  487. print(s.contains(3))    #False  
  488.   
  489.   
  490. #函数式工具   部分地应用函数创建新函数  
  491. def exp(base, power):  
  492.     return base ** power  
  493.   
  494. def two_to_the(power):  
  495.     return (exp(2,power))  
  496. # print(two_to_the(3))    # 8  
  497.   
  498. from functools import partial  
  499. two_to_the = partial(exp,2)  
  500. # print(two_to_the(3))   # 8  
  501.   
  502. square_of = partial(exp,power = 2)  
  503. # print(square_of(3))    # 9  
  504.   
  505. def double(x):  
  506.     return x*x  
  507.   
  508. xs = [1,2,3,4]  
  509. twice_xs = [double(x) for x in xs]  #[1, 4, 9, 16]  
  510. twice_xs = list(map(double,xs))     #python3中输出的是map对象,如果想跟list一样输出,需要转为list  
  511. list_doubler = partial(map ,double)  
  512. twice_xs = list_doubler(xs)  
  513. # print(list(twice_xs))  
  514.   
  515.   
  516. def multiply(x,y):return x*y  
  517. products = map(multiply,[1,2],[4,5])    #  1*4  2*5   [4, 10]  
  518. # print(list(products))  
  519.   
  520. def is_even(x):  
  521.     """True if x is even , False if x is odd"""  
  522.     return x%2 == 0  
  523. x_evens = [x for  x in xs if is_even(x)]   #[2, 4]  
  524. x_evens = filter(is_even,xs)         #<filter object at 0x00000000049294E0>  
  525. # print(list(x_evens))    #[2, 4]  
  526.   
  527. list_evener = partial(filter,is_even)  
  528. x_evens = list_evener(xs)  
  529. # print(list(x_evens))    #[2, 4]  
  530.   
  531. import functools  
  532. x_product = functools.reduce(multiply,xs)     #python3把reduce放在了functools包中,功能:一步步计算  
  533. list_product = partial(functools.reduce,multiply)  
  534. x_product = list_product(xs)  
  535. # print(x_product)          #    24  
  536.   
  537. #枚举  
  538. #有时候可能想在一个列表上迭代,并且同时使用它的元素和元素的索引  
  539.   
  540. #非python用法  
  541. documents = ""   #这是一个文档  
  542. for i in range(len(documents)):  
  543.     document = documents[i]  
  544.     print(document)  
  545. #非python用法  
  546. i = 0  
  547. for document in documents:  
  548.     print(document,i)  
  549.     i += 1  
  550.   
  551. #python惯用的解决方案是使用枚举(enumerate),它会产生(index,element)元组:  
  552. for i, document in enumerate(documents):  
  553.     print(i,document)  
  554.   
  555. #类似的,如果只想要索引,则执行  
  556. for i in range(len(documents)):print(i)        #非python用法  
  557. for i, _ in enumerate(documents):print(i)      #python用法  
  558.   
  559. #压缩和参数拆分  
  560. #如果想把两个或多个列表压缩到一起,可以使用zip把多个列表转换为一个对应元素的元组的单个列表中  
  561. list1 = ['a''b''c']  
  562. list2 = [1,2,3,4]          #如果列表的长度各异,zip会在第一个列表结束时停止  
  563. z = zip(list1,list2)  
  564. # print(list(z))     #[('a', 1), ('b', 2), ('c', 3)]  
  565.   
  566. #可以用一种特殊的方法解压列表  
  567. list3, list4 = zip(*z)    #*执行参数拆分(argument unpacking)  
  568. # print(list3, list4)     #('a', 'b', 'c') (1, 2, 3)  
  569.   
  570. #可以在任何函数上使用参数拆分  
  571. def add(a, b):return a + b  
  572. # print(add(1,2))    #  3  
  573. # print(add([1,2]))   #TypeError  
  574. # print(add(*[1,2]))   #3  
  575.   
  576.   
  577. #args和kwargs  
  578. #假如我们想创建一个更高阶的函数,把某个函数f作为输入,并返回一个对任意输入都返回f值两倍的新函数  
  579. def doubler(f):  
  580.     def g(x):  
  581.         return 2*f(x)  
  582.     return g  
  583.   
  584. def f1(x):  
  585.     return x+1  
  586.   
  587. g = doubler(f1)  
  588. # print(g(3))     #   8  
  589. # print(g(-1))    #   0  
  590.   
  591. def f2(x,y):  
  592.     return x+y  
  593. # g = doubler(f2)   #TypeError: g() takes 1 positional argument but 2 were given  
  594. # print(g(1,2))  
  595.   
  596. def magic(*args, **kwargs):  
  597.     print("unnamed args:",args)  
  598.     print("keyword args:",kwargs)  
  599. magic(1,2,key = "word", key2 = "word2")   #   unnamed args: (1, 2)  
  600.                                             #   keyword args: {'key': 'word', 'key2': 'word2'}  
  601.   
  602. def other_way_magic(x,y,z):  
  603.     return x+y+z  
  604. x_y_list = [1,2]  
  605. z_dict = {"z":3}  
  606. # print(other_way_magic(*x_y_list,**z_dict))     # 6  
  607. #我们将会只用它来创建可以将任意参数作为输入的高阶函数  
  608.   
  609. def doubler_correct(f):  
  610.     """works no matter what kind of inputs of expects"""  
  611.     def g(*args, **kwargs):  
  612.         """whatever arguments g is supplied, pass them through to f"""  
  613.         return 2*f(*args,**kwargs)  
  614.     return g  
  615. g = doubler_correct(f2)       #  6  
  616. # print(g(1,2))  
  617.   
  618.   
  619. exit(0)  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python笔记.md 是一个用于记录Python编程相关内容的markdown文档。 在Python学习过程中,学习者通常会遇到各种问题和疑惑,需要有一个地方来记录学习笔记和重要概念,以方便日后复习和查阅。Python笔记.md 就是一个很好的选择。 Python笔记.md 可以按照自己的需要来组织内容,比如可以分为不同的章节或主题,并使用markdown语法来格式化文档,使其更加清晰易读。 在Python笔记.md中,可以记录Python的基础语法、常用数据结构、函数、类、模块等内容。此外,还可以记录一些常见的错误和解决方法,以便日后遇到类似问题时能够快速找到解决方案。 Python笔记.md 还可以用来记录自己的思考和理解。在学习过程中,我们常常会思考某个概念或代码背后的原理,这时候可以将自己的思考记录在笔记中,以便后续复习和回顾。 使用Python笔记.md 还可以方便与他人分享学习心得。可以在文档中加入注释或标题,使得文档更加易读和友好。同时,也可以将Python笔记.md 推送到版本控制系统中,与他人共享和共同编辑。 总之,Python笔记.md 是一个非常有用的工具,可以帮助学习者系统地记录、整理和复习Python编程相关的知识和经验。无论是初学者还是有经验的开发者,都可以从中受益,并提高自己的编程技能。 ### 回答2: Python笔记.md是一个使用Markdown语法编写的Python笔记文档。Markdown语法是一种轻量级的标记语言,可以快速地编辑和排版文档。 在Python笔记.md中,可以记录Python程序设计的相关知识、概念和技巧。通过使用Markdown语法,可以方便地插入代码块、链接、图片以及其他强调和排版格式,使得笔记更加直观和易读。 Python笔记.md可以按照不同的章节和主题组织内容,方便快速查找和阅读。在每个章节中,可以记录不同的Python编程概念,如数据类型、控制结构、函数、类等。可以通过示例代码和解释说明来详细解释这些概念的用法和特点。 在笔记中,还可以记录一些Python的常见问题和解决方案,例如常见错误、调试技巧等。这些内容可以帮助初学者更好地理解和掌握Python语言。 此外,Python笔记.md还可以连接到其他的Python资源,如官方文档、教程、在线代码编辑器等。这样可以提供更多的学习和参考资料。 总之,Python笔记.md是一个有条理、易读和方便编辑的Python学习笔记文档,可以帮助人们更好地学习和理解Python编程语言。 ### 回答3: Python笔记md是一种用来记录Python编程语言相关内容的文本文件格式。它使用Markdown语法来快速、简洁地编写和格式化笔记Python笔记md的优点是: 1. 简单易懂:Markdown语法简洁明了,使用起来非常简单,即便没有编程背景的人也能快速上手。 2. 跨平台兼容:无论是在Windows、Mac还是Linux系统中,Python笔记md都可以轻松使用。 3. 可读性强:Python笔记md的文本格式使得代码和说明可以同时显示,方便读者理解和学习。 4. 方便分享和发布:Python笔记md可以导出为HTML或PDF格式,方便分享给其他人或者发布到网络上。 5. 与开发工具兼容:大多数集成开发环境(IDE)和文本编辑器都支持Markdown语法,可以实时预览和编辑笔记。 使用Python笔记md可以帮助程序员记录代码和相关的解释和说明,方便复习和查看。它还可以用于编写技术博客、文档和教育材料等。而且由于其文本格式的特点,Python笔记md也非常适合使用版本控制系统进行版本管理。 总而言之,Python笔记md是一种简单、灵活且易于分享的笔记格式,可以有效提高编程学习和开发的效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值