Python介绍

在本文中,我们将介绍Python的基础知识。 我们越来越接近目标,总的来说,我们将很快开始使用Data Science的主要库,并将使用TensorFlow(对于编写和部署神经网络,您将了解深度学习)。

安装方式


可以从python.org下载Python。 但是,如果尚未安装,则改为
我建议使用Anaconda分发软件包,该软件包已经包含了数据科学领域所需的大多数库。

如果您不使用Anaconda发行版,请确保安装pip软件包管理器,这使安装第三方软件包变得容易,因为我们将需要其中的一些软件包。 还值得安装更加用户友好的交互式IPython shell。 请记住,Anaconda发行版随附pip和IPython。

空格


许多编程语言使用区分代码块。
大括号。 缩进在Python中使用:

#      for for i in [ 1, 2, 3, 4, 5] : print (i) #     for i for j in (1, 2, , 4, 5 ] : print ( j ) #     for j print (i + j) #     for j print (i) #     for i print ( "  ") 

这使代码易于阅读,但同时使其遵循格式。 括号和方括号内的空格将被忽略,这使得编写冗长的表达式变得更加容易:

 #    long_winded_computation = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20) 

且易于阅读的代码:
 #   list_of_lists = [ [ 1 , 2, 3 ) , [4, 5, 6 ] , [ 7 , 8, 9 ] ] #      easy_to_read_list_of_lists = [1, 2, 3 ) , [4, 5, 6 ) , [7, 8, 9 ) ] 

为了继续执行该语句,在下一行使用反斜杠,但是很少使用这样的记录:

 two_plus_three = 2 + \ 3 

用空格格式化代码使得很难将代码复制和粘贴到Python shell中。 例如,尝试复制以下代码:

 for i in [ 1, 2, 3, 4, 5] : #      print (1) 

进入标准的Python Shell将抛出错误:

 #    :     IndentationError : expected an indented blk 

因为对于解释器,空字符串表示带for循环的代码块的结尾。

IPython具有“%paste”魔术功能,可以将所有内容正确粘贴到剪贴板上,包括空格。

模块(导入库)


某些基于Python的编程环境库默认情况下未加载。 为了使用这些工具,必须导入包含它们的模块。

一种方法是简单地导入模块本身:

 import re my_regex = re.compile ("[0-9]+",re.I) 

re是模块的名称,其中包含用于使用正则表达式的函数和常量。 通过以这种方式导入整个模块,可以通过在函数前面加上re来访问它们。

如果代码中已经有一个名称为re的变量,则可以使用模块别名:

 import re as regex my_regex = regex.compile("[0-9)+",regex.I) 

在导入的模块名称繁琐或模块频繁访问模块的情况下,也可以使用别名。

例如,当基于matplotlib模块可视化数据时,通常
使用以下标准别名:

 import matplotlib.pyplot as plt 

如果需要从模块中获取几个特定值,则可以显式导入它们,并不受限制地使用:

 from collections import defaultdict , Counter lookup = defaultdict(int) my_counter = Counter() 

功能介绍


函数是接受零个或多个输入参数并返回相应结果的规则。 在Python中,通常使用def语句定义函数:

 def double() : """,  ,     docstring,  ,    . ,       2""" return  * 2 

Python中的函数被视为一流的对象。 这意味着可以将它们分配给变量并以与其他任何参数相同的方式传递给其他函数:

 #   f   def apply_to_one(f): '""'  f      """ return f(1) my _ double = double #       = apply_to_one(my_double) # = 2 

此外,您可以轻松创建简短的匿名函数或lambda表达式:

  = apply_to_one(lambda :  + 4) # = 5 

Lambda表达式可以分配给变量。 但是,建议使用def运算符:

 another double = lmbd : 2 *  #    def another_double (x) : return 2 *  #   

此外,您可以将默认参数传递给函数参数,仅当期望使用非默认值时才应指定该参数:

 def my_print (message="oe   " ): print (message ) my_print ( "pe") #  '' my_print () #  '   ' 

有时建议通过名称指定参数:

 #   def subtract ( a=0, =0 ) : return  - b subtract (10, 5)#  5 subtract (0, 5)#  -5 subtract (b=5 )#  ,      

将来,功能将被经常使用。

线数


两侧的字符串(或字符序列)仅限于单引号或双引号(必须匹配):

 single_quoted_string = '    ' #  double_quoted_string = "  " #  

反斜杠用于编码特殊字符。 例如:

 tab_string = "\t" #    len (tab_string)# = 1 

如果需要反斜杠本身,则直接出现
在Windows操作系统的目录名称中,然后使用r'“'创建一个未格式化的字符串

 not_tab_string = r"\t" #   ' \ '  ' t ' len (not_tab_string) # = 2 

使用三重单行(或
双引号):

 multi_line_string = """   .        """ 

例外情况


当出现问题时,Python会引发异常。 未处理的异常会导致程序意外停止。 使用tryexcept 语句处理异常:

 try: print (0 / 0) except ZeroDivisionError : rint ( "    ") 

尽管在许多编程语言中,异常的使用被认为是一种不良的编程风格,但是在Python中,无需担心使用异常来使代码更整洁,有时我们会这样做。

清单


列表中可能是Python中最重要的数据结构。 这只是一个有序集合(或集合),类似于其他编程语言中的数组,但具有附加功能。

 integer_list = [1, 2, ] #    heterogeneous_list = ["", 0.1 , True] #   list_of_lists = [integer_list, heterogeneous_list, [] ] #   list_length = len(integer_list) #  = 3 list_sum = sum(integer_list)#    = 6 

您可以设置值并使用方括号访问列表的第n个元素:

  = list(range (10)) #   {0, 1 , . . . , 9] zero =  [0] # = 0 ,  -, .  .  1-  = 0 one = x [1] # = 1 nine =  [-1] # = 9, -    eight =  [-2] # = 8, -     [0] = -1 #   = { - 1 , 1 , 2, 3, . . . , 9] 

另外,方括号用于“剪切”列表:

 first_three = [:] #   = [-1 , 1, 2] three_to_end = [3:] #    = {3, 4, ... , 9] one_to_four = [1:5] #     = {1 , 2, 3, 4] last_three = [-3:] #   = { 7, 8, 9] without_first_and_last = x[1:-1] #     = {1 , 2, ... , 8] _ of _ = [:] #   = [ -1, 1, 2, ... , 91 

Python有一个ln语句,用于检查元素是否属于列表:

 1 ln [1, 2, 3] #True 0 ln [1, 2, 3] #False 

该检查包括一次查看所有元素,因此,只有在确定列表很小或检查时间不重要的情况下,才应使用它。

列表很容易链接在一起:

  = [1, 2, 3] . extend ( [ 4, 5, 6] ) #   = {1, 2, 3, 4, 5, 6} 

如果要保留列表x不变,则可以使用列表的附加项:

  = [1, 2, 3]  =  + [4, 5, 6] #= (1, 2, 3, 4, 5, 6] ;    

通常,一个操作将一个元素添加到列表中:

  = [1, 2, 3] x.append (0)#   = [1,2,3,0] =  [-1] # = 0 z = len (x)# = 4 

如果您知道列表包含多少个元素,通常可以方便地将其解压缩:

 ,  = [1, 2] #   = 1,  = 2 

如果表达式两侧的元素数量不同,则会显示ValueError错误消息。

对于丢弃的值,通常使用下划线:

 _,  = [1, 2] #   == 2,     

元组


元组是列表的不可变(或不可变)表亲。

几乎可以使用列表完成的所有事情都可以通过元组完成,而无需对其进行更改。 用圆括号代替元括号,而不使用方括号,或者完全不用圆括号即可:

 my_list = [1, 2] #   my_tuple = (1, 2) #   other_tuple = 3, 4 #    my_list [1] = 3 #  my_list = [1 , 3] try: my_tuple [1] = 3 except ypeError : print ( "   " ) 

元组提供了一种从函数返回多个值的便捷方法:

 #        def sum_and_product (x,  ) : return ( + ) , ( * ) sp = sum_and_product (2, 3) # = (5, 6) s,  = sum_and_product (S, 10) # s = 15,  = 50 

元组(和列表)也用于多种分配中:

 ,  = 1, 2 #   = 1,  = 2 ,  = ,  #   -;   = 2,  = 1 

辞典


字典或关联列表是另一种基本数据结构。

其中,值与键相关联,这使您可以快速检索与特定键相对应的值:

 empty_dict = {} #   - empty_dict2 = dict () #   - grades = { "Grigoriy" : 80, "Tim" : 95 } #   (  ) 

可以使用方括号访问键值:

 rigory_aleksee = grades[ "Grigoriy"] # = 80 

如果您尝试请求不在词典中的值,则会收到KeyError错误消息:

 try: kates_grade = grades [ "Kate "] except eyError: rint ( "    ! " ) 

您可以使用in运算符检查密钥:

 grigoriy_has_grade = "Grigoriy" in grades #true kate_has_grade = "Kate" in grades #false 

字典有一个get()方法,当寻找丢失的键时,它不会抛出异常,而是返回默认值:

 grigoriy_grade = grades. get ( "Grigoriy ", 0) # =80 kates_grade = grades.get ("Kate" , 0) # = 0 no_ones_grade = grades.get ( "No One" ) #    = None 

键值分配使用相同的方括号执行:

 grades [ "Tim" ] = 99 #    grades [ "Kate"] = 100 #    num_students = len(grades) # = 3 

字典通常用作表示结构化结构的简便方法
资料:

 tweet = { "user" : " grinaleks", "text" : "   -  ", " retweet_count" : 100, "hashtags " : [ "# data", " #science", " #datascience " , " #awesome", "#yolo" ] } 

除了搜索单个键之外,您还可以一次与所有人联系:

 tweet_keys = tweet.keys() #   tweet_values = tweet.values() #   tweet_items = tweet.items() #   (, ) "user" in tweet_keys # True,    in  "user" in tweet # -,   in  "grinaleks" in tweet_values # True 

键必须是不可变的; 特别是列表不能用作键。 如果需要组合键,则最好使用元组或找到将键转换为字符串的方法。

Defaultdict字典


让文档需要数词。 解决该问题的明显方法是创建一个字典,其中的键是单词,值是单词的出现频率(或文本中单词出现的次数)。 在单词检查期间,如果当前单词已在字典中,则其频率会增加,如果不存在,则会将其添加到字典中:

 #   word_ counts = { } document = { } #  ;    for word in document : if word in word counts: word_counts [word] += 1 else : word_counts [word] = 1 

另外,您可以利用一种称为“比请求权限更好的方法”的方法,并在尝试访问丢失的密钥时捕获错误:

 word_ counts = { } for word in document : try: word_counts [word] += 1 except eyError : word_counts [word] = 1 

第三个技巧是使用get()方法,该方法可以很好地克服缺少键的情况:

 word_counts = { } for word in document : previous_count = word_counts.get (word, 0) word_counts [word] = previous_count + 1 

所有这些技术都比较麻烦,因此,建议使用defaultdict字典(也称为带有默认值的字典)。 它看起来像是常规词典,但有一个功能-尝试访问其中不存在的键时,它首先使用不带参数的函数为其添加一个值,该函数是在创建时提供的。 要使用defaultdict字典,必须从collections模块导入它们:

 from collections import defaultdict word_counts = defaultdict(int) # int ()  0 for word in document : word_counts[word] += 1 

此外,在使用列表,字典甚至使用用户定义的函数时,defaultdict字典的使用非常实用:

 dd_list = defaultdict (list)# list ()    dd_list [2].append (l) #  dd_list  (2: {1] } dd_dict = defaultdict (dict ) # dict ()    dict dd_dict ["Grigoriy"] [ "City" ] = "Seattle" # { "Grigoriy" : { "City" : Seattle"} dd_pair = defaultdict (lambda: [0,0] ) dd_pair [2][1] = 1 #  dd_pair  (2 : {0,1] } 

当词典用于“收集”时,将需要这些功能
某个键的结果,以及何时有必要避免重复
检查字典中是否存在键。

反字典


计数器字典的子类将值的序列转换为类似defaultdict(int)的对象,在该对象中,键被映射到频率,或更精确地,键以频率显示(映射)。

它主要在创建直方图时使用:

 from collections import Counter  = Counter([0,1,2,0]) #    = { 0 : 2, 1 : 1, 2 : 1 } 

它的功能使其很容易解决字数统计问题:

 #      word_counts = Counter (document) 

计数器字典具有most_common()方法,该方法通常非常有用:

 #  10       () for word, count in word_counts.most_common(10) : print (word, count ) 

许多


set或set数据结构是无序元素的集合,没有重复:

 s = set ()#    s.add (1) #  s = { 1 } s.add (2) #  s = { 1, 2 } s.add (2) # s    = { 1, 2 }  = len (s) # = 2  = 2 in s # = True z = 3 in s # = False 

之所以使用很多,有两个原因。 首先,在机上操作非常快。 如果您需要检查大量元素是否属于某个序列,那么集合数据结构比列表更适合于此:

 #  - stopwords_list = [ "a", "an" , "at "] + hundreds_of_other_words + [ "yet ", " you"] " zip" in stopwords_list # False,     #  - stopwords_set = set(stopwords_list) " zip" in stopwords_set #    

第二个原因是要在数据集中获得唯一元素:

 item_list = [1, 2, 3, 1, 2, 3] #  num_items = len( item_list) #  = 6 item_set = set(item_list) #   (1, 2, 3} num_distinct_items = len(item_set) #   = 3 distinct_item_list = list(item_set) #    = [1,2,3] 

与字典和列表相比,使用它们的频率要低得多。

控制结构


与大多数其他编程语言一样,可以使用if语句按条件执行操作:

 if 1 > 2: message " 1    2 . . . " elif 1 > 3: message "elif  'else if '" else: message = "      ,  else " 

此外,您可以使用单行三元if-then-else运算符,该运算符有时会在以后使用:

 parity = "" if  % 2 ===  else " " 

Python有一个whlle循环:

  = 0 while  < 10: print (x, " 10")  += 1 

但是,for循环将更常与in运算符一起使用:

 for  in range (lO) : print (x, " 10" ) 51 

如果您需要更复杂的回路控制逻辑,则可以使用运算符

 continue  break: for  1n range (10) : 1f  == 3: continue #      if  == 5: break print (x) #    

结果,将打印0、1、2和4。

真实性


Python中的布尔变量与大多数其他编程语言的工作方式相同,只有一个例外-大写字母:

 one_is_less_than_two = 1 < 2 #True true_equals_false = True == False #False 

为了指示不存在的值,使用了特殊的None对象,该对象在其他语言中对应于null:

  = None print (x == None )#  True,    - print (  is None ) #  True - 

Python可以使用需要布尔值布尔类型的任何值。 以下所有元素的布尔值均为False:

  • 错误的 。
  • 设置()(设置):
  • [](空列表);
  • {}(空字典);

几乎所有其他一切都被认为是真实的。 这使得使用if语句检查空列表变得容易。 空行,空字典等。但是,有时,如果您不考虑以下因素,则会导致难以识别的错误:

 s = some_function_that_returns_a_string () #    if s: first_char = s [0] #     else: first char = "" 

这是一种更简单的方法:

 first_char = s and s [0] 
因为逻辑运算符and返回第二个值(如果第一个为true),则返回第一个值(如果为false)。 同样,如果以下表达式中的x是数字,或者可能是None,则结果将以某种方式是数字:

 safe  =  or 0 #   

Python内置的all函数获取一个列表,并且仅在每个列表项为true时返回True,而any内置函数在至少一个元素为true时返回true:

 all ( [True, 1, { 3 }]) # True all ( [True, 1, {}] ) # False, {} =  any ( [ True, 1, {}]) # True, True =  all ( [] ) # True,      any ( [ ] ) # False,      

Source: https://habr.com/ru/post/zh-CN450474/


All Articles