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

Case Analysis of Common skills in Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Most people do not understand the knowledge points of this "case analysis of common Python skills" article, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Python common skills case analysis" article.

1. String inversion

Use Python slices to reverse the string:

# Reversing a string using slicing my_string = "ABCDE" reversed_string = my_string [::-1] print (reversed_string) # Output# EDCBA2. Capitalize the first letter of each word

Use the title function method:

My_string = "my name is chaitanya baweja" # using the title () function of string classnew_string = my_string.title () print (new_string) # Output# My Name Is Chaitanya Baweja3. String lookup unique element

Use the concept of a collection to find the unique element of a string:

My_string = "aavvccccddddeee" # converting the string to a settemp_set = set (my_string) # stitching set into a string using joinnew_string = '.join (temp_set) print (new_string) # output# cdvae4. Repeat printing strings and lists n times

You can use the multiplication symbol (*) to print a string or list multiple times:

N = 3 # number of repetitions my_string = "abcd" my_list = [1 print (my_string*n) # abcdabcdabcd print (my_list*n) # [1, 2, 3, 1, 2, 3] 5. The list is generated by # Multiplying each element ina list by 2 original_list = [1 Multiplying each element ina list by 2 for x in original_list 3 Jing 4] new_list = [2 Jing x for x in original_list] print (new_list) # [2 Jing 4 Jing 6 Jing 8] 6. Variable exchange a = 1b = 2a, b = b, a print (a) # 2print (b) # 17. Split a string into a list of substrings

Use the .split () function:

String_1 = "My name is Chaitanya Baweja" string_2 = "sample/ string 2" # default separator''print (string_1.split ()) # [' My', 'name',' is', 'Chaitanya',' Baweja'] # defining separator as'/ 'print (string_2.split (' /')) # ['sample',' string 2'] 8. Multiple strings are combined into a single string list_of_strings = ['My',' name', 'is',' Chaitanya', 'Baweja'] # Using join with the comma separatorprint (','. Join (list_of_strings)) # Output# My,name,is,Chaitanya,Baweja9. Check whether the string is a palindrome my_string = "abcba" if my_string = = my_string [::-1]: print ("palindrome") else: print ("not palindrome") # Output# palindrome10. Statistics on the number of elements in the list # finding frequency of each element in a listfrom collections import Counter my_list = ['axiajiajiajiajiajiajiajiaozhuangyuzhuo] count = Counter (my_list) # defining a counter object print (count) # Of all elements# Counter ({' dice: 5, 'baked: 3,' axiom: 2) 'print: 1}) print (count [' b']) # of individual element# 3 print (count.most_common (1)) # most frequent element# [('dumped, 5)] 11. Determine whether two strings are Anagrams

Anagrams means that in two words, each English word (without case) appears the same number of times. Use the Counter class to determine whether the two strings are Anagrams.

From collections import Counter str_1, str_2, str_3 = "acbde", "abced", "abcda" cnt_1, cnt_2, cnt_3 = Counter (str_1), Counter (str_2), Counter (str_3) if cnt_1 = = cnt_2: print ('1 and 2 anagram') if cnt_1 = = cnt_3: print ('1 and 3 anagram') # output# 1 and 2 anagram12. Use the try-except-else-block module

Except get exception handling:

A, b = 1 try: print (a Run this always) # exception raised when b is 0except ZeroDivisionError: print ("division by zero") else: print ("no exceptions raised") finally: print ("Run this always") # output# division by zero# Run this always13. Use the enumeration function to get key/value pairs my_list = ['asides,' breads, 'caches,' dudes,'e'] for index, value in enumerate (my_list): print ('{0}: {1} '.format (index, value)) # 0: a # 1: B # 2: C # 3: d # 4: E14. Check the memory usage of the object import sys num = 21 print (sys.getsizeof (num)) # In Python 2,2 memory In Python 3, 2815. Merge dictionary dict_1 = {'apple': 9,' banana': 6} dict_2 = {'banana': 4,' orange': 8} combined_dict = {* * dict_1, * * dict_2} print (combined_dict) # Output# {'apple': 9,' banana': 4, 'orange': 8} 16. Calculate the time it takes to execute a piece of code

Use the time class to calculate the time it takes to run a piece of code:

Import time start_time = time.time () # Code to check followsfor i in range (10cm 5): a, b = 1Magne2 c = a + b # Code to check endsend_time = time.time () time_taken_in_micro = (end_time- start_time) * (10mm Q6) print (time_taken_in_micro) # output# 18770.21789550781217. Expand the list: from iteration_utilities import deepflatten # if you only have one depth nested_list, use thisdef flatten (l): return [item for sublist in l for item in sublist] l = [[1dje 2 item for sublist in l for item in sublist 3], [3]] print (flatten (l)) # [1je 2jue 3, 3] # if you don't know how deep the list is nestedl = [[1je 2jue 3], [4, [5], [6jue 7]], [8, [9, [10] print (deepflatten (l) Depth=3)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 18. List sampling import random my_list = ['axiang,' baked, 'cached,' dashed,'e'] num_samples = 2 samples = random.sample (my_list,num_samples) print (samples) # ['axiom,' e'] this will have any 2 random values19. Digitization

Convert integers to a list of numbers

Num = 123456 # using maplist_of_digits = list (map (int, str (num)) print (list_of_digits) # [1,2,3,4,5,6] # using list comprehensionlist_of_digits = [int (x) for x in str (num)] print (list_of_digits) # [1,2,3,4,5,6] 20. Check the uniqueness of list elements

Check that each element in the list is unique:

Def unique (l): if len (l) = = len (set (l)): print ("All elements are unique") else: print ("List has duplicates") unique ([1mai 2je 3 List has duplicates 4]) # All elements are unique unique ([1MJ 2J 3]) # List has duplicates above is about the content of this article entitled "case Analysis of Common Python skills". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about it, please follow the industry information channel.

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