好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python初学者必学的20个重要技巧

本文转载自公众号“读芯术”(ID:AI_Discovery)。

Python是世界上使用最广泛的编程语言之一,原因有很多:易理解、用途非常广泛、包含了大量的模块和库等等。其中,简洁和较高的可读性使Python在所有软件中非常突出。

作为一名数据科学家,笔者每天都在使用Python,这是笔者工作的一个重要部分。在这个过程中,笔者学会了一些惊人的技巧。

1. 交换价值

数字交换通常涉及存储在临时变量中的值。然而,我们可以通过使用Python技巧中的一行代码,不需要使用瞬变变量就可以实现这一点。

"""valueswapping""" 
           a, b=5, 10 
           print(a, b)           a, bb= b, a           print(a, b)           output           10, 5

2. 列表中所有项的一个字符串

必须对一个字符串列表进行卷积时,可以通过for循环来更新每一项以此连续不断地执行此操作。然而这样做很麻烦,特别是在列表很长的情况下。在Python中,字符串是不可变的。因此,在每两个拼接中,左字符串和右字符串都应该被复制成一个新的字符串。

如下所示,使用join()函数是一种更为简洁的解决方法:

p = ["Python", "is", "a","popular", "language"] 
print(" ".join(p))output 
Python is a popular language

3. 列表中最常见的元素

确定列表中最经常出现的值。如果不同的项目以相同的方式出现,则打印其中的一个。创建列表集以删除冗余值。因此在集合中能找到每一项的最大事件数,然后再考虑最大的。

list1 = [0, 1, 2, 3, 3, 2, 3, 1, 4, 5, 4] 
print(max(set(list1), key = list1.count))output 
3

4. 测试两个字符串是否为相同字母异序词

defanagram(string_1,string_2):     
                      """Test if the stringsare anagrams.     
                      string_1: string     
                      string_2: string     
                      returns: boolean     
                      """

解决上述问题,从而弄清楚两个字符串是否是相同字母异序词。给定两个字符串string_1 和string_2,测试这两个字符串是否互为相同字母异序词。

from collections importCounter 
           defanagram(string_1,string_2):                    returnCounter(string_1) ==Counter(string_2)           anagram('pqrs','rqsp') 
           True 
           anagram('pqrs','rqqs') 
           False

图源:unsplash

5. 逆转字符串

切片是Python中的一种方便技巧,它还可以用于逆转字符串中项的顺序。

# with slicing 
       str ="PQRST" 
       reverse_str = str[::-1] 
       print(reverse_str)       Output       TSRQP

6. 反转列表

使用这种方法创建列表的副本,而且列表没有按顺序排序。要创建一个副本,需要更多的空间来容纳所有现有的元素。

# using slicing approach 
        defReverse(lst):         lstlst1 = lst[::-1] 
         return lst1 
                 lst = [5, 6, 7, 8, 9, 10] 
        print(Reverse(lst)) 
        output 
        [10, 9, 8, 7, 6, 5]

7. 转置矩阵

转置矩阵意味着将列变换为行,反之亦然。使用Python,可以通过以下代码与zip函数结合,并使用*工具解压缩矩阵的转置列表。

mat=[(5,6,7),(8,9,10),(11,12,13),(14,15,16)] 
                                             for row in mat: 
                                              print(row) 
                                             print("\n") 
                                             t_mat=zip(*mat) 
                                             for row in t_mat: 
                                              print(row) 
                                             output 
                                             (5, 6, 7) 
                                             (8, 9, 10) 
                                             (11, 12, 13) 
                                             (14, 15, 16) 
                                             (5, 8, 11, 14) 
                                             (6, 9, 12, 15) 
                                             (7, 10, 13, 16)

8. 链式比较

在编程中,测试两个以上的条件是很正常的。假设需要测试以下内容:

p < q< r

更聪明的做法确实是在Python中通过链式来编写。任务链表示如下:

if p< q< r: 
    {.....}

返回布尔值来比较判断正确与否。示例如下:

# chaining comparison 
          a =3 
          print(1< a<10) 
          print(5< a<15) 
          print(a <7< a*7<49) 
          print(8> a<=6) 
          print(3== a>2) 
          output 
          True 
          False 
          True 
          True 
          True

9. ‘get’字典

下面是访问Python字典中键值的传统方法:

dict = {"P":1, "Q":2} 
print(dict["P"]) 
print(dict["R"])

代码的第三行会产生一个关键错误:

Traceback (most recent call last): 
  File ".\dict.py", line 3, in 
    print (dict["R"]) 
KeyError: 'R'

为了防止这种情况的出现,可以使用get()函数。当在字典中可用时,该技巧可以提供特定键的值。若不可用,则不会返回任何值(如果 get()只使用了一个参数)。

dict = {"P":1, "Q":2} 
       print(dict.get("P")) 
       print(dict.get("R")) 
       print(dict.get("R","Unavailable! ")) 
       output       1 
       None 
       Unavailable!

10. 按值给字典排序

排序在日常编程中一直是很有用的。Python中的字典在许多应用程序中被广泛使用,范围从竞争领域到开发人员领域。构造一本字典,并按字母顺序显示所有键,按值列出按字母顺序排序的键和值。

defdict():  
       keyval ={}       # Initializing the value       keyval[3] =48 
       keyval[2] =6 
       keyval[5] =10 
       keyval[1] =22 
       keyval[6] =15 
       keyval[4] =245 
       print ("Task3:-\nKeys and Values sorted", 
       "in alphabetical order by thevalue") 
       # Remember this would arrange inaphabetical sequence       # Convert it to float to mathematicalpurposes       print(sorted(keyval.elements(), key = 
          lambda k_val:(k_val[1], k_val[0]))) 
       defmain():        dict()                  if __name__=="__main__":  
        main()       output 
       [(2, 6), (5, 10), (6, 15), (1, 22), (3, 48), (4, 245)]

图源:unsplash

11. 列表推导

要从不同的迭代中构造新的列表,需要使用列表推导。由于列表推导式产生列表,因此它们包含表达式的括号,该表达式将被执行到每个元素。推导列表更简单,因为Python解释器旨在检测循环中的循环模式。

# Multiplying each item in the list with 3 
           list1 = [2,4,6,8] 
           list2 = [3*p for p in list1] 
           print(list2) 
           [6,12,18,24]

12. 执行部分计划所花费的时间

这个重点展示了计算程序或程序的一部分执行所花费的时间。计算时间有助于优化Python脚本,使其执行得更好。

import time 
      initial_Time = time.time() 
      # Program to test follows      x, y=5,6 
      z = x+ y      # Program to test ending      ending_Time = time.time() 
      Time_lapsed_in_Micro_sec= (ending_Time- initial_Time)*(10**6) 
      print(" Timelapsed in micro_seconds: {0} ms").format(Time_lapsed_in_Micro_sec)

13. 合并字典

这是Python中的一个重要技巧:使用一个表达式来合并两个字典并将结果存储在第三个字典中。单个表达式是 **,这不会影响其他两个字典。**表示参数是一个字典。使用**是一种快捷方式,这样就可以通过使用字典直接向函数传递多个参数。

使用这个函数,首先将第一个字典的所有元素传递给第三个字典,然后将第二个字典传递给第三个字典。这将替换第一个字典的重复键

dic1 = {'men': 6, 'boy': 5} 
       dic2 = {'boy': 3, 'girl': 5} 
       merged_dic = {**dic1, **dic2} 
       print(merged_dic) 
       Output 
       {'men': 6, 'boy': 3, 'girl': 5}

14. 数字化

下面是使用了 map()函数、列表推导以及一种更简单的数字化方法编写的代码:

number =2468 
      # with map 
      digit_list =list(map(int, str(number))) 
      print(digit_list)      [2, 4, 6, 8] 
      # with list comprehension 
      digit_list = [int(a) for a instr(number)] 
      print(digit_list)      [2, 4, 6, 8] 
      # Even simpler approach      digit_list =list(str(number)) 
      print(digit_list)      [2, 4, 6, 8]

15. 测试独特性

一些列表操作要求测试列表中的所有项是否完全不同。尝试在列表中执行集合操作时,通常会发生这种情况,这个特殊的实用程序在这时必不可少。

defuniq(list): 
              iflen(list)==len(set(list)):                   print("totalitems are unique") 
              else: 
                   print("Listincludes duplicate item") 
           uniq([0,2,4,6]) 
           total items are unique           uniq([1,3,3,5]) 
           List includesduplicate item

16. 使用枚举

在循环中使用枚举数可以快速查找索引:

sample_list = [4, 5, 6] 
           for j, item inenumerate(sample_list): 
             print(j, ': ', item) 
           Output 
           0 : 4 
           1 : 5 
           2 : 6

17. 在一行中计算任意数的阶乘

此技巧可以帮助你在一行中找到一个给定数的阶乘:

import functools 
         fact = (lambda i: functools.reduce(int.__mul__, range(1,i+1),1)(4) 
         print(fact) 
         Output         24

18. 返回几个函数的元素

许多计算机语言都不提供这个功能。但是对于Python,函数会产生几个元素。查看下面的实例,了解它是如何执行的:

# function returning several elements. 
         defa(): 
             return5, 6, 7, 8 
         # Calling the abovefunction. 
         w, x, y, z=a() 
         print(w, x, y, z) 
         Output 
         5678

19. 加入一个真正的Python切换大小写语句

下面是使用字典复制大小写转换结构的脚本:

defaswitch(a): 
             returnaswitch._system_dic.get(a, None) 
           aswitch._system_dic = {'mangoes': 4, 'apples': 6, 'oranges': 8} 
           print(aswitch('default')) 
           print(aswitch('oranges')) 
           Output           None 
           8

20. 使用splat操作符解包函数参数

splat操作符提供了一种解包参数列表的有效方法:

deftest(a, b, c): 
         print(p, q, r) 
       test_Dic = {'a': 4, 'b': 5, 'c': 6} 
       test_List = [10, 11, 12]       test(*test_Dic) 
       test(**test_Dic) 
       test(*test_List) 
       #1-> p q r 
       #2-> 4 5 6 
       #3-> 10 11 12

掌握这些小技巧,快速有效地完成Python任务。

【责任编辑:赵宁宁 TEL:(010)68476606】

查看更多关于Python初学者必学的20个重要技巧的详细内容...

  阅读:25次