Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summarize the Python skills worth learning.

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "summing up Python skills worth learning". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1 string inversion

Use slices to reverse the string.

Str1= "qwert" rev_str1=str1 [::-1] # output # trewq

2 capitalize the initials

Converts a string to uppercase. Using the title () method.

Str1= "this is a book" print (str1.title ()) # This Is A Book

3 find a unique element in a string

The following code can be used to find all the unique elements in the string.

Str1= "aabbccccdddd" setset1=set (str1) new_str=''.join (set1) print (new_str)

4 repeatedly print a string or list

In the following code, use (*) for a string or list. Copy the string or list multiple times.

IFei 4 str1= "abcd" list1= [1Magne 2] print (str1*i) # abcdabcdabcdabcd print (list1*i) # [1JI 2 Jing 1 Jing 2 Jing 1 Jing 2]

5 list derivation

List derivation provides us with a good way to create lists based on other lists. The following code creates a new list by multiplying each element of the old list by 2.

List1= [1pr 2pr 3] new_list1= [2 * i for i in list1] # [2pr 4pr 6]

6 exchange variables

Implement variable exchange without using another variable.

Print (x) # 2 print (y) # 1

7 split the string into a list of substrings

We use the .split () method in the string class to split the string into a list of substrings, and you can pass the delimiter to be split as an argument.

Str1= "This is a book" str2= "test/ str2" print (str1.split ()) # ['This',' is', 'aura,' book'] print (str2.split ('/')) # ['test',' str2']

8 combine a list of strings into a single string

Join () combines the list of strings passed as parameters into a single string. In this case, we use comma delimiters to separate them.

List_str= ['This','is','a','book'] print (', '.join (list_str)) # This,is,a,book

9 check back the text string

We have discussed how to reverse strings, so palindromes are very easy to judge in Python.

Str1= "qqaabb" if str1==str1 [::-1]: print ("palindrome") else: print ("not") # No

10 element statistics in the list

Use the Python Counter class. The Python counter tracks the frequency of each element in the container, and Counter () returns a dictionary with the element as the key and the frequency as the value.

In addition, use the most_common () function to get the elements in the list that appear the most.

From collections import Counter list1= [count=Counter (list1) print (count) print (count ['b']) print (count.most_common (1))

11 to judge whether two strings are disordered words

Disordered words are words or phrases formed by rearranging the letters of different words or phrases. If the Counter objects of two strings are equal, then they are the same alphabetic out-of-order word pairs.

S1 acbde, "abced", "abcda" C1 recorder c2, Counter (S2), Counter (S3) if c1==c2: print ('1 and 2 are disordered words') if c1==c3: print ('1 and 3 are disordered words')

12 use try-except-else blocks

Try / except is an exception handling module in Python. Adding an else statement will run without throwing an exception in the try block.

An exception except ZeroDivisionError: print ("divisor is 0") else: print ("no exception") finally: print ("this segment is always executed") is triggered when a try banner 1 try: print (a beat b) # b is 0)

13 get index / value pairs through enumeration

You can use the following script to traverse the values in the list and their indexes.

List1= [for idx,val in enumerate (list1): print ('{0}: {1} '.format (idx,val)) # 0VlV a # 1VlV b # 2VOV c # 3WR d # 4VOE

14 get the memory usage information of the object

The following script can be used to check the memory usage information of an object.

Import sys num=21 print (sys.getsizeof (num))

15 merge two dictionaries

In Python 2, using update () to merge two dictionaries makes Python 3 easier.

In the following script, two dictionaries are merged. In the case of intersection, use the value in the second dictionary.

Dic1= {'app':9,'banana':6} dic2= {' banana':4,'orange':8} com_dict= {* * dic1,**dic2} # {'apple':9,'banana':4,'orange':8}

16 calculate the time required for code execution

The following code uses library functions to calculate how many milliseconds it takes to execute the code.

Import time s_time=time.time () 2 c=a+b e_time=time.time () time_taken_in_micro= (e_time-stime) * (10 minutes 6) print ("milliseconds: {0} ms" .format (time_taken_in_micro))

17 expand the list list

Sometimes you don't know the nesting depth of the list, and you just want to put all the elements in a normal list. You can get the data through the following methods:

From iteration_utilities import deepflatten # if the depth of a nested list is only 1 layer def flatten (l): return [item for sublist in l for item in sublist] l = [[1 item for sublist in l for item in sublist] 3], [3]] print (flatten (l)) # [1 flatten (l)) # if you don't know the depth of list nesting l = [1, 2], [4, [5], [6]], [8, [9, [10] print (deepflatten (l) Depth=3)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

18 random sampling from the list

The following code generates n random samples from a given list.

Import random list1= [ns=2 samples=random.sample (list1,ns) print (samples) # ['axiomagol]

Or use the secrets library to generate random samples, and the following code applies only to Python 3.x.

Import secrets s_rand=secrets.SystemRanom () list1= ['axiaojie'] ns=2 samples=s_rand.sample (list1,ns) print (samples) # ['cedar']

19 digital listing

The following code converts integers to a list of numbers.

Nums=123456 # uses map digit_list=list (map (int,str (nums) print (digit_list) # [1 map 2 for x in str 3 5 5] # uses the list expression digit_list= [int (x) for x in str (nums)] print (digit_list) # [1 digit_list 2 3 4 5]

20 uniqueness check

The following function checks whether the elements in the list are unique.

Def unique (l): if len (l) = = len (set (l)): print ("all elements are unique") else: print ("there is repetition") unique ([1meme 2jort 3jin4]) # all elements are unique unique ([1mie 1meme 3p4]) # there are repetitions of "summing up Python skills worth learning". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report