In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the Python script to improve the coding speed of what are the tips, the article is very detailed, has a certain reference value, interested friends must read it!
1. Find a unique element in a string
The following code snippet can be used to find all unique elements in a string. We use that all elements in the collection are unique attributes.
My_string = "aavvccccddddeee" # convert a string to a collection temp_set = set (my_string) # use join to set splicing to the string new_string = '.join (temp_set) print (new_string)
two。 Initials are capitalized
The following code snippet can be used to convert a string to title case. This is done using the method of the title () string class.
My_string = "My Name Is Chaitanya Baweja" # use the title () function of the string class new_string = my_string.title () print (new_string) # output My Name Is Chaitanya Baweja
3. Reverse string
The following code snippet uses the Python slicing operation to reverse the string.
# use slicing to reverse the string my_string = "ABCDE" reversed_string = my_string [::-1] print (reversed_string) # output
4. Print a string or list n times
You can use multiplication (*) on strings or lists. This allows us to multiply them at will.
N = 3 # repetition times my_string = "ABCD" my_list = [1 my_string 2 my_list 3] print (my_string * n) # abcdabcdabcd print (my_list * n) # [1, 2, 3, 1, 2, 3, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1,
An interesting use case is to define a list with constant values-assuming zero.
N = 4 my_list = [0] * n # n indicates the length of the required list # [0pc0p0p0p0pl 0]
5. Combine a list of strings into a single string
The join () method combines the list of strings passed as parameters into a single string. In our case, we use comma delimiters to separate them.
List_of_strings = ['My',' name', 'is',' ', 'lulu'] # concatenate the string print (','. Join (list_of_strings)) # Output # My,name,is,,lulu using ","
6. Exchange values between two variables
Python makes it very easy to exchange values between two variables without using another variable.
A = 1 b = 2 a, b = b, a print (a) # 2 print (b) # 1
7. Split a string into a list of substrings
We can split the string into a list of substrings using the .split () method in the string class. You can also pass the delimiter to be split as a parameter.
String_1 = "My name is lulu" string_2 = "sample/ string 2" # default separator''print (string_1.split ()) # [' My', 'name',' is', '',' lulu'] # defining separator as'/ 'print (string_2.split (' /')) # ['sample',' string 2']
8.List Comprehension
List Comprehension gives us an elegant way to create lists based on other lists. The following code snippet creates a new list by multiplying each element of the old list by 2.
# Multiplying each element ina list by 2 original_list = [1 Multiplying each element ina list by 2 for x in original_list 3 4] new_list = [2 beacon x for x in original_list] print (new_list) # [2 recollection 4 Jing 6 Jing 8]
You can learn more here.
9. Check whether the given string is a palindrome
We have discussed how to reverse strings. So palindrome becomes a simple program in Python.
My_string = "abcba" if my_string = = my_string [::-1]: print ("palindrome") else: print ("not palindrome") # Output # palindrome
10. Use enumerations to get index / value pairs
The following script uses enumerations to traverse the values in the list and their indexes.
My_list = ['await,' baked, 'caged,' dumped,'e'] for index, value in enumerate (my_list): print ('{0}: {1} '.format (index, value)) # 0: a # 1: B # 2: C # 3: d # 4: e
11. Find out whether two strings are letters
An interesting use of the Counter class is to find crossword puzzles.
Crossword puzzles are words or phrases formed by rearranging the letters of different words or phrases.
If the objects of two Counter strings are equal, then they are crossword puzzles.
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')
twelve。 Use try-except-else blocks
Error handling in Python can be easily done using try / except blocks. When no exception is thrown in the try block, it will run normally. If you need to run some programs without considering exceptions, use finally to ensure the release of resources and the final execution of the logic.
Try: print (a bank b) # exception raised when b is 0 except ZeroDivisionError: print ("division by zero") else: print ("no exceptions raised") finally: print ("Run this always")
13. The frequency of the elements in the list
There are many ways to do this, but my favorite is to use the Python Counter class.
The Python counter tracks the frequency of each element in the container. Counter () returns a dictionary where the element is the key and the frequency is the value.
We also use the most_common () function to get the elements in the most_frequent list.
# finding frequency of each element in a list from collections import Counter my_list = [count = Counter (my_list) # defining a counter object print (count) # Of all elements # Counter ({'dudes: 5,' baked: 3, 'asides: 2) 'censor: 1}) print (count [' b']) # of individual element # 3 print (count.most_common (1)) # most frequent element # [('dumped, 5)]
14. Check the memory usage of an object
The following script can be used to check the memory usage of an object. Learn more here.
Import sys num = 21 print (sys.getsizeof (num)) # In Python 2,24 # In Python 3,28
15. Sample from the list
The following code snippet n uses the random library to generate many random samples from a given list.
Random import my_list = ['axiaqunzhuo'] num_samples = 2 samples = random. Sample (my_list,num_samples) print (sample) # ['axie'] this will have any 2 random values
16. Count the time required for code execution
The following code snippet uses the time library to calculate the time it takes to execute a piece of code.
Import time start_time = time.time () # Code to check follows a, b = 1Magol 2 c = a + b # Code to check ends end_time = time.time () time_taken_in_micro = (end_time- start_time) * (10 years 6) print ("Time taken in micro_seconds: {0} ms") .format (time_taken_in_micro)
17. Flattening list list
Sometimes you are uncertain about the nesting depth of the list, and you just want to put all the elements in a flat list. This should be done:
From iteration_utilities import deepflatten # if you only have one depth nested_list, use this def flatten (l): return [item for sublist in l for item in sublist] l = [[1dje 2dag3], [3]] print (flatten (l)) # [1LYI 2LECHO 3,3] # if you don't know how deep the list is nested l = [[1MIT 2LING 3], [4, [5], [6JE7]], [8, [9, [10] print (deepflatten (l) Depth=3)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
18. Merge two dictionaries
In Python 2, we use the update () method to merge the two dictionaries. Python 3.5 makes this process easier. In the script given below, the two dictionaries are merged. Where there is an intersection, use the values in the second 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} above are all the contents of this article entitled "what are the tips for Python scripts to improve coding speed"? thank you for reading! Hope to share the content to help you, more related knowledge, welcome to 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.