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

How to use Python code

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "how to use Python code". Many people will encounter such a dilemma in the operation of actual cases, 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. Reverse string

The following code uses the Python slice operation to reverse the string.

# Reversing a string using slicing my_string = "ABCDE" reversed_string = my_string [::-1] print (reversed_string) # Output # EDCBA

two。 Use the title class (initials capitalized)

The following code can be used to convert a string to a title class. This is done by using the title () method in the string class.

My_string = "my name is chaitanya baweja" # using the title () function of string class new_string = my_string.title () print (new_string) # Output # My Name Is Chaitanya Baweja

3. Find the only element of a string

The following code can be used to find all the unique features in a string. We use its attributes, where all the elements in a set of strings are unique.

My_string = "aavvccccddddeee" # converting the string to a set temp_set = set (my_string) # stitching set into a string using join new_string = .join (temp_set) print (new_string)

4. Output a string or list n times

You can use multiplication (*) on strings or lists. In this way, you can multiply them as much as you want.

N = 3 # number of repetitions my_string = "abcd" my_list = [1Magol 2JE3] print (my_string*n) # abcdabcdabcd print (my_list*n) # [1MJ 2JI 3J 1J 2J 3J 1J 2J 3J 1M 2J 3] import streamlit as st

An interesting use case is to define a list with constant values, assuming zero.

N = 4 my_list = [0] * n # n denotes the length of the required list # [0,0,0,0]

5. List parsing

Based on other lists, list parsing provides an elegant way to create lists.

The following code creates a new list by multiplying each object of the old list twice.

# 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]

6. The exchange value between two variables

Python can easily exchange values between two variables without using a third variable.

A = 1 b = 2 a, b = b, a print (a) # 2 print (b) # 1

7. Split a string into a list of substrings

By using the .split () method, you can divide a string into a list of substrings. You can also pass the delimiter you want to split as a parameter.

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. Consolidate a list of strings into a single string

The join () method merges a list of strings into a single string. In the following example, use the comma delimiter to separate them.

List_of_strings = [My,name,is,Chaitanya,Baweja] # Using join with the comma separator print (, .join (list_of_strings)) # Output # My,name,is,Chaitanya,Baweja

9. Check whether the given string is a palindrome (Palindrome)

Reversing the string has been discussed above. Therefore, palindromes become a simple program in Python.

My_string = "abcba" if my_string = = my_string [::-1]: print ("palindrome") else: print ("not palindrome") # Output # palindrome

10. Feature frequency of the list

There are many ways to do this, and I like to use Python's Counter class best. The Python counter tracks the frequency of each element, and Counter () feeds back a dictionary, where the element is the key and the frequency is the value.

You also use the most_common () function to get the most_frequent element in the list.

# finding frequency of each element in a list from collections import Counter my_list = [a, a, b, b, b, c, d, d] count = Counter (my_list) # defining a counter object print (count) # Of all elements # Counter ({d: 5, b: 3, a: 2, c: 1}) print (count [b]) # of individual element # 3 print (count.most_common (1)) # most frequent element # [(d, 5)]

11. Find whether two strings are anagrams

An interesting use of the Counter class is to find anagrams.

Anagrams refers to a new word or word formed by reordering the letters of different words or words.

If the counter objects of two strings are equal, then they 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)

twelve。 Use try-except-else blocks

Error handling in Python is easily resolved by using try/except blocks. It may be useful to add an else statement to this block. When there is no exception in the try block, it runs normally.

If you want to run some programs, use finally without considering the exception.

A, b = 1 try 0 try: print (a Run this always b) # exception raised when b is 0 except ZeroDivisionError: print ("division by zero") else: print ("no exceptions raised") finally: print ("Run this always")

13. Use enumerations to get indexes and value pairs

The following script uses enumerations to iterate over the values in the list and their indexes.

My_list = [a, b, c, d, e] for index, value in enumerate (my_list): print ({0}: {1} .format (index, value)) # 0: a # 1: B # 2: C # 3: d # 4: e

14. Check the memory usage of an object

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

Import sys num = 21 print (sys.getsizeof (num)) # In Python 2,24 # In Python 3,28

15. Merge two dictionaries

In Python 2, the update () method is used to merge two dictionaries, while Python3.5 makes the operation easier.

In a given script, two dictionaries are merged. We used the values in the second dictionary to avoid crossover.

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. The time it takes to execute a piece of code

The following code uses the time software 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. List flattening

Sometimes you are not sure about the nesting depth of the list, and you just want all the elements to be in a single flat list.

It can be obtained in the following ways:

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]

If you have an array that is correctly formatted, Numpy flattening is a better choice.

18. List sampling

Using the random software library, the following code generates n random samples from a given list.

Import random my_list = [a, b, c, d, e] num_samples = 2 samples = random.sample (my_list,num_samples) print (samples) # [a, e] this will have any 2 random values

It is highly recommended to use the secrets software library to generate random samples for encryption.

The following code is limited to Python 3 only.

Import secrets # imports secure module. Secure_random = secrets.SystemRandom () # creates a secure random object. My_list = [a, b, c, d, e] num_samples = 2 samples = secure_random.sample (my_list, num_samples) print (samples) # [e, d] this will have any 2 random values

19. Digitization

The following code converts an integer to a list of numbers.

Num = 123456 # using map list_of_digits = list (map (int, str (num)) print (list_of_digits) # [1,2,3,4,5,6] # using list comprehension list_of_digits = [int (x) for x in str (num)] print (list_of_digits) # [1,2,3,4,5,6]

20. Check uniqueness

The following function checks whether all features in a list are unique.

Def unique (l): if len (l) = = len (set (l)): print ("All elements are unique") else: print ("List has duplicates") unique ([1mai 2je 3je 4]) # All elements are unique unique ([1Min 1Min 2jue 3]) # List has duplicates "how to use Python Code" ends here. Thank you for your 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